Tuyệt vời! Tôi đã thử nó nhưng không thể tìm cách sử dụng nó để mã hóa một tin nhắn. Dường như không có bất kỳ chức năng "Mã hóa" nào
Mẫu MSDN này cho System.Security.Cryptography.ECDiffieHellmanCng
.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
class Alice
{
public static byte[] alicePublicKey;
public static void Main(string[] args)
{
using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng())
{
alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
alice.HashAlgorithm = CngAlgorithm.Sha256;
alicePublicKey = alice.PublicKey.ToByteArray();
Bob bob = new Bob();
CngKey k = CngKey.Import(bob.bobPublicKey, CngKeyBlobFormat.EccPublicBlob);
byte[] aliceKey = alice.DeriveKeyMaterial(CngKey.Import(bob.bobPublicKey, CngKeyBlobFormat.EccPublicBlob));
byte[] encryptedMessage = null;
byte[] iv = null;
Send(aliceKey, "Secret message", out encryptedMessage, out iv);
bob.Receive(encryptedMessage, iv);
}
}
private static void Send(byte[] key, string secretMessage, out byte[] encryptedMessage, out byte[] iv)
{
using (Aes aes = new AesCryptoServiceProvider())
{
aes.Key = key;
iv = aes.IV;
// Encrypt the message
using (MemoryStream ciphertext = new MemoryStream())
using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] plaintextMessage = Encoding.UTF8.GetBytes(secretMessage);
cs.Write(plaintextMessage, 0, plaintextMessage.Length);
cs.Close();
encryptedMessage = ciphertext.ToArray();
}
}
}
}
public class Bob
{
public byte[] bobPublicKey;
private byte[] bobKey;
public Bob()
{
using (ECDiffieHellmanCng bob = new ECDiffieHellmanCng())
{
bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
bob.HashAlgorithm = CngAlgorithm.Sha256;
bobPublicKey = bob.PublicKey.ToByteArray();
bobKey = bob.DeriveKeyMaterial(CngKey.Import(Alice.alicePublicKey, CngKeyBlobFormat.EccPublicBlob));
}
}
public void Receive(byte[] encryptedMessage, byte[] iv)
{
using (Aes aes = new AesCryptoServiceProvider())
{
aes.Key = bobKey;
aes.IV = iv;
// Decrypt the message
using (MemoryStream plaintext = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(plaintext, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(encryptedMessage, 0, encryptedMessage.Length);
cs.Close();
string message = Encoding.UTF8.GetString(plaintext.ToArray());
Console.WriteLine(message);
}
}
}
}
}
Nguồn
2015-01-20 08:09:28
Cảm ơn Chochos. Tôi đã sử dụng thành công thư viện Lâu đài Bouncy. Đó là ít khó khăn để tìm tài liệu mặc dù! :) – Hemant
Lần phát hành cuối cùng cho C# là 1.7, ngày 7 tháng 4 năm 2011, cho Java 1.51, ngày 27 tháng 7 năm 2014. Đối với các dự án C# tôi không thích Lâu đài Bouncy, vì thiếu các tính năng và không được duy trì mã. –
Lưu ý rằng ECC trong BouncyCastle cho C# rất chậm và dễ bị tấn công theo thời gian. – CodesInChaos