📄 cryptographer.cs
字号:
using System;
using System.Collections.Generic;
using System.Text;
using DiffieHellmanMerkle;
using System.IO;
using System.Security.Cryptography;
namespace TestEllipticCurveDiffieHellman
{
public class Cryptographer
{
private byte[] _externalPublicKey;
private byte[] _secretKey;
private byte[] _cipherText;
private byte[] _IVByteArray = Encoding.Unicode.GetBytes("initialV");
private ECDiffieHellmanMerkle myECDH;
public byte[] ExternalPublicKey
{
get { return _externalPublicKey; }
set { _externalPublicKey = value; }
}
public byte[] PublicKey
{
get { return myECDH.PublicKey; }
}
public byte[] SecretKey
{
get { return _secretKey; }
set { _secretKey = value; }
}
public byte[] CipherText
{
get { return _cipherText; }
set { _cipherText = value; }
}
public void CreatePublicPrivateKey()
{
myECDH = new ECDiffieHellmanMerkle(ECDHAlgorithm.ECDH_384);
myECDH.KeyDerivationFunction = ECDHKeyDerivationFunction.HASH;
myECDH.HashAlgorithm = DerivedKeyHashAlgorithm.SHA256_ALGORITHM;
}
public void SendPublicKey(Cryptographer cryptographer)
{
cryptographer.ExternalPublicKey = myECDH.PublicKey;
}
public void DeriveSecretKey()
{
_secretKey = myECDH.RetrieveSecretKey(_externalPublicKey);
}
public void EncryptMessage(string secretMessage)
{
byte[] SecretMessageByteArray = Encoding.Unicode.GetBytes(secretMessage);
RijndaelManaged rijndael = new RijndaelManaged();
ICryptoTransform encryptor = rijndael.CreateEncryptor(_secretKey, _IVByteArray);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(SecretMessageByteArray, 0, SecretMessageByteArray.Length);
cryptoStream.FlushFinalBlock();
_cipherText = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
}
public void SendEncryptedMessage(Cryptographer cryptographer)
{
cryptographer.CipherText = _cipherText;
}
public string DecryptMessage()
{
RijndaelManaged rijndael = new RijndaelManaged();
ICryptoTransform decryptor = rijndael.CreateDecryptor(_secretKey, _IVByteArray);
MemoryStream memoryStream = new MemoryStream(_cipherText);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] clearText = new byte[_cipherText.Length];
int clearTextByteSize = cryptoStream.Read(clearText, 0, clearText.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.Unicode.GetString(clearText);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -