protected string Encrypt(string blob, string externalKey) { var self = new ECDiffieHellmanCng(); self.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; self.HashAlgorithm = CngAlgorithm.Sha256; publicKey = Convert.ToBase64String(self.PublicKey.ToByteArray()); var externalKeyBytes = Convert.FromBase64String(externalKey); var externalKeyObject = ECDiffieHellmanCngPublicKey.FromByteArray(externalKeyBytes, CngKeyBlobFormat.GenericPublicBlob); var sharedSecret = self.DeriveKeyMaterial(externalKeyObject); var aes = new AesManaged(); aes.Key = sharedSecret; aes.GenerateIV(); var transform = aes.CreateEncryptor(); using (var memoryStream = new MemoryStream()) { var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); var data = Encoding.ASCII.GetBytes(blob); cryptoStream.Write(data, 0, data.Length); cryptoStream.Close(); var encryptedData = memoryStream.ToArray(); blob = Convert.ToBase64String(encryptedData); self.Dispose(); aes.Dispose(); return(AddEncryptionHeaders(blob)); } }
private static void BobReceivesData(byte[] encryptedData) { Console.WriteLine("Bob receives encrypted data"); byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize / 8; //获取IV长度 byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; ++i) { iv[i] = encryptedData[i]; //读出非加密的IV } using (var bobAlgorithm = new ECDiffieHellmanCng(bobKey)) { using (CngKey alicePKey = CngKey.Import(alicePubKey, CngKeyBlobFormat.EccPublicBlob)) { //混合生成AES密钥 和上面生成的相同 byte[] symkey = bobAlgorithm.DeriveKeyMaterial(alicePKey); Console.WriteLine("Bob creates this symmetric key with Alices public key information: {0}", Convert.ToBase64String(symkey)); aes.Key = symkey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) { using (MemoryStream ms = new MemoryStream()) { var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); //解密数据 cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to: {0}", Encoding.UTF8.GetString(rawData)); //转换为字符串并打印 } } aes.Clear(); } } }
private static byte[] AliceSendsData(string message) { Console.WriteLine("Alice sends message: {0}", message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(aliceKey)) using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice creates this symmetric key with " + "Bobs public key information: {0}", Convert.ToBase64String(symmKey)); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { // create CryptoStream and encrypt data to send var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); // write initialization vector not encrypted ms.Write(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); cs.Close(); encryptedData = ms.ToArray(); } aes.Clear(); } } Console.WriteLine("Alice: message is encrypted: {0}", Convert.ToBase64String(encryptedData));; Console.WriteLine(); return(encryptedData); }
public static byte[] CompleteEcdhFromStream(CngKey pcPrivate, Stream message) { using (var inputStream = new BinaryReader(message, Encoding.UTF8, true)) { var ecdhKeyLen = inputStream.ReadInt32(); var ecdhKeyBytes = inputStream.ReadBytes(ecdhKeyLen); using (var ecdh = new ECDiffieHellmanCng(pcPrivate)) { ecdh.HashAlgorithm = CngAlgorithm.Sha256; ecdh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; using (var mobilePublic = CngKey.Import(EncryptionUtils.PemToEccBlob(ecdhKeyBytes), CngKeyBlobFormat.EccPublicBlob)) { return(ecdh.DeriveKeyMaterial(mobilePublic)); } } } }
public void TestGenerateSecret() { string keyString = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs"; byte[] keyBytes = Base64Url.Decode(keyString); ECDiffieHellmanPublicKey clientKey = CryptoUtils.CreateEcDiffieHellmanPublicKey(keyString); ECDiffieHellmanCng ecKey = new ECDiffieHellmanCng(384); ecKey.HashAlgorithm = CngAlgorithm.Sha256; ecKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ecKey.SecretPrepend = new byte[128]; // Server token //ecKey.SecretPrepend = new byte[0]; // Server token Console.WriteLine(ecKey.HashAlgorithm); Console.WriteLine(ecKey.KeyExchangeAlgorithm); byte[] secret = ecKey.DeriveKeyMaterial(clientKey); }
private static Aes DeriveKeyAndIv(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] nonce) { privateKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; privateKey.HashAlgorithm = CngAlgorithm.Sha256; privateKey.SecretAppend = nonce; byte[] keyAndIv = privateKey.DeriveKeyMaterial(publicKey); byte[] key = new byte[16]; Array.Copy(keyAndIv, 0, key, 0, 16); byte[] iv = new byte[16]; Array.Copy(keyAndIv, 16, iv, 0, 16); Aes aes = new AesManaged(); aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; return(aes); }
public static void Equivalence_Hash(HashAlgorithmName algorithm, bool prepend, bool append) { using (ECDiffieHellmanCng ecdh = NewDefaultECDHCng()) using (ECDiffieHellmanPublicKey publicKey = ecdh.PublicKey) { byte[] secretPrepend = prepend ? new byte[3] : null; byte[] secretAppend = append ? new byte[4] : null; byte[] newWay = ecdh.DeriveKeyFromHash(publicKey, algorithm, secretPrepend, secretAppend); ecdh.HashAlgorithm = new CngAlgorithm(algorithm.Name); ecdh.SecretPrepend = secretPrepend; ecdh.SecretAppend = secretAppend; ecdh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; byte[] oldWay = ecdh.DeriveKeyMaterial(publicKey); Assert.Equal(newWay, oldWay); } }
public static void Main(string[] args) { // The most simple example creates a new ECDiffieHellmanCng with no // parameters, but an overload of such constructor accepts a key // size. // Valid key sizes are 256, 384, and 521 bits. using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng(keySize)) { 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); } }
public void InitDiffieHellman_ShouldGenerateSameDerivedKeys() //imitating client to test encrypting { ECDiffieHellmanCng eCDiffie = new ECDiffieHellmanCng(256); eCDiffie.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; eCDiffie.HashAlgorithm = CngAlgorithm.Sha256; byte[] myPublicKey = eCDiffie.ExportSubjectPublicKeyInfo(); //export in x509 format String myPublicKeyBase64 = Convert.ToBase64String(myPublicKey); //Passing to project var packetToPreoject = new Packet('0', Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Concat("{", String.Format("\"Public_key\": \"{0}\"", myPublicKeyBase64), "}")))); ServiceProcessor.UserLoggedIn stubMethod = StubMethod; PacketProcessor packetProcessor = new PacketProcessor(stubMethod); Packet response = packetProcessor.Process(packetToPreoject); PublicKeyPayload serverPublicKey = JsonSerializer.Deserialize <PublicKeyPayload>(Convert.FromBase64String(response.Payload)); byte[] otherKeyFromBase64 = Convert.FromBase64String(serverPublicKey.Public_key); ECDiffieHellmanCng eCDiffie2 = new ECDiffieHellmanCng(256); eCDiffie2.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; eCDiffie2.HashAlgorithm = CngAlgorithm.Sha256; int some = 0; eCDiffie2.ImportSubjectPublicKeyInfo(otherKeyFromBase64, out some); byte[] otherKeyDecoded = eCDiffie2.PublicKey.ToByteArray(); CngKey k = CngKey.Import(otherKeyDecoded, CngKeyBlobFormat.EccPublicBlob); byte[] derivedKey = eCDiffie.DeriveKeyMaterial(k); string actual = Convert.ToBase64String(packetProcessor.EncryptionModule.DerivedKey); string expected = Convert.ToBase64String(derivedKey); Assert.Equal(expected, actual); }
private void OnPeerConnected(NetIncomingMessage message) { var hailMessage = message.SenderConnection.RemoteHailMessage; if (hailMessage == null) { message.SenderConnection.Deny(); ClientModel.Logger.WriteWarning("ConnectionId is null [Message: {0}, SenderEndPoint: {1}]", message.ToString(), message.SenderEndPoint); return; } var connectionId = hailMessage.ReadString(); var publicKeySize = hailMessage.ReadInt32(); var publicKeyBlob = hailMessage.ReadBytes(publicKeySize); var publicKey = CngKey.Import(publicKeyBlob, CngKeyBlobFormat.EccPublicBlob); var key = _diffieHellman.DeriveKeyMaterial(publicKey); message.SenderConnection.Tag = connectionId; lock (_syncObject) { // Add connection packer var packer = new Packer(); packer.SetKey(key); _packers.Add(connectionId, packer); // Invoke waiting commands List <WaitingCommandContainer> commands; if (_waitingCommands.TryGetValue(connectionId, out commands)) { foreach (var command in commands) { SendMessage(connectionId, command.Package, command.RawData, command.Unreliable); } _waitingCommands.Remove(connectionId); } } ClientModel.Logger.WriteDebug("AsyncPeer.PeerConnected({0})", connectionId); }
public Object deriveBits(jwkPublicKey publicKey, string hashAlgorithmName) { CngAlgorithm alg = selectCngCurve(publicKey.crv); // Generate a new key pair CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters(); keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport; keyCreationParameters.KeyUsage = CngKeyUsages.KeyAgreement; CngKey serverKeyPair = CngKey.Create(alg, null, keyCreationParameters); CngKey clientPubicKey = publicKey.toPublicCngKey(); ECDiffieHellmanCng ecdh = new ECDiffieHellmanCng(serverKeyPair); ecdh.HashAlgorithm = selectCngHashAlgorithm(hashAlgorithmName); byte[] keyMaterial = ecdh.DeriveKeyMaterial(clientPubicKey); return(new object[] { new jwkPublicKey(serverKeyPair), keyMaterial }); }
public async Task <byte[]> RoseSendsDataAsync(string msg) { Console.WriteLine($"Rose's message is {msg}"); byte[] rawData = Encoding.UTF8.GetBytes(msg); byte[] encryptedData = null; using (var roseAlgorithm = new ECDiffieHellmanCng(roseKey)) using (CngKey jackPubKey = CngKey.Import(jackPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { //使用Jack的公钥和Rose的密钥对生成一个对称密钥 byte[] symmKey = roseAlgorithm.DeriveKeyMaterial(jackPubKey); Console.WriteLine($"The symmetric key is {Convert.ToBase64String(symmKey)}"); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { //创建CryptoStream来加密数据并发送 using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { await ms.WriteAsync(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } aes.Clear(); } } Console.WriteLine($"the ecrypted data is {Convert.ToBase64String(encryptedData)}"); Console.WriteLine(); return(encryptedData); }
private async Task BobReceivesDataAsync(byte[] encryptedData) { WriteLine("Bob receives encrypted data"); byte[] rawData = null; var aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) { iv[i] = encryptedData[i]; } using (var bobAlgorithm = new ECDiffieHellmanCng(_bobKey)) using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); WriteLine("Bob creates this symmetric key with " + $"Alices public key information: {Convert.ToBase64String(symmKey)}"); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { await cs.WriteAsync(encryptedData, nBytes, encryptedData.Length - nBytes); } rawData = ms.ToArray(); WriteLine($"Bob decrypts message to: {Encoding.UTF8.GetString(rawData)}"); } aes.Clear(); } }
private Cryptography.AES256 ECDH_Client() { Cryptography.AES256 aes; using (ECDiffieHellmanCng dh = new ECDiffieHellmanCng()) { dh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; dh.HashAlgorithm = CngAlgorithm.Sha256; byte[] publicKey = dh.PublicKey.ToByteArray(); byte[] sharekey = new byte[publicKey.Length]; socket.Receive(sharekey, publicKey.Length, SocketFlags.None); socket.Send(publicKey, publicKey.Length, SocketFlags.None); byte[] key = dh.DeriveKeyMaterial(CngKey.Import(sharekey, CngKeyBlobFormat.EccPublicBlob)); aes = new Cryptography.AES256(key); } this.aes = aes; while (true) { byte[] iv = CryptoReceiveMsg(); CryptoSend(iv, PacketType.Response); var pack = CryptoReceive(); if (pack.header == PacketType.Retry) { continue; } else if (pack.header == PacketType.Fail) { IPEndPoint iep = (IPEndPoint)(socket.RemoteEndPoint); Console.WriteLine("ERROR [Host " + iep.Address + ":" + iep.Port + "] Connection test with text is failed"); this.aes = null; return(null); } else if (pack.header == PacketType.OK) { aes.aes.IV = iv; break; } } return(aes); }
static byte[] ExchangeKey(Socket socket) { Console.WriteLine("exchange key..."); using (var dh = new ECDiffieHellmanCng()) { dh.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; dh.HashAlgorithm = CngAlgorithm.Sha256; var publicKey = dh.PublicKey.ToByteArray(); Console.WriteLine("\tpublic key: {0}", BytesToString(publicKey)); Send(socket, HmacKey, publicKey, 0, publicKey.Length); var otherKey = new byte[publicKey.Length]; Receive(socket, HmacKey, otherKey, 0); Console.WriteLine("\tother key: {0}", BytesToString(otherKey)); var key = dh.DeriveKeyMaterial(CngKey.Import(otherKey, CngKeyBlobFormat.EccPublicBlob)); Console.WriteLine("key exchanged: {0}", BytesToString(key)); return(key); } }
public static void Test() { ECDiffieHellmanCng alice = new ECDiffieHellmanCng(); alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; alice.HashAlgorithm = CngAlgorithm.Sha1; ECDiffieHellmanCng bob = new ECDiffieHellmanCng(); bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; bob.HashAlgorithm = CngAlgorithm.Sha1; byte[] aliceKey = alice.DeriveKeyMaterial(bob.PublicKey); byte[] bobKey = bob.DeriveKeyMaterial(alice.PublicKey); Console.WriteLine(bobKey.SequenceEqual(aliceKey)); var r = new RijndaelManaged(); r.GenerateIV(); var iv = r.IV; byte[] encrypted = SymmetricAlgorithmTest.Encrypt <RijndaelManaged>(original, bobKey, iv); string roundtrip = SymmetricAlgorithmTest.Decrypt <RijndaelManaged>(encrypted, aliceKey, iv); string hex = Epic.Converters.HexString.Encode(encrypted); string base64 = Convert.ToBase64String(encrypted); //Display the original data and the decrypted data. Console.WriteLine($"ECC:"); Console.WriteLine("Byte: {0}", encrypted.Length); Console.WriteLine("Hex: {0}, {1}", hex.Length, hex); Console.WriteLine("Base64: {0}, {1}", base64.Length, base64); Console.WriteLine("Decode: {0}", roundtrip); Console.WriteLine(); }
private byte [] AliceSendData(string message) { Console.WriteLine("Alice message: {0}", message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encData = null; //Get alice's algorithm (use alice keys) ECDiffieHellmanCng aliceAlg = new ECDiffieHellmanCng(aliceKey); using (CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { //Create symmetric key - using alice's keys and bob's public key byte[] symKey = aliceAlg.DeriveKeyMaterial(bobPubKey); //Provider for data encryption AesCryptoServiceProvider acsp = new AesCryptoServiceProvider(); acsp.Key = symKey; acsp.GenerateIV(); using (ICryptoTransform encryptor = acsp.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { //Create crypto stream CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); //Send initial vector ms.Write(acsp.IV, 0, acsp.IV.Length); //Send encrypted data cs.Write(rawData, 0, rawData.Length); //Important thing! cs.Close(); encData = ms.ToArray(); } acsp.Clear(); } Console.WriteLine("Alice cipher: {0}", Convert.ToBase64String(encData)); return(encData); }
private static void InitializeEncryption() { if (ENC_ECDCrypto == null || DEC_ECDCrypto == null) { ENC_ECDCrypto = new ECDiffieHellmanCng { KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash, HashAlgorithm = CngAlgorithm.Sha256 }; ENCpublicKey = ENC_ECDCrypto.PublicKey.ToByteArray(); DEC_ECDCrypto = new ECDiffieHellmanCng { KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash, HashAlgorithm = CngAlgorithm.Sha256 }; DECpublicKey = DEC_ECDCrypto.PublicKey.ToByteArray(); ENCprivateKey = ENC_ECDCrypto.DeriveKeyMaterial(CngKey.Import(DECpublicKey, CngKeyBlobFormat.EccPublicBlob)); DECprivateKey = DEC_ECDCrypto.DeriveKeyMaterial(CngKey.Import(ENCpublicKey, CngKeyBlobFormat.EccPublicBlob)); } }
static internal byte[] PerformAssymetricKeyExchangeUsingECDiffieHellmanOnSocket(System.Net.Sockets.Socket socket) { using (ECDiffieHellmanCng ECDiffieHellmanCngobj = new ECDiffieHellmanCng()) { ECDiffieHellmanCngobj.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ECDiffieHellmanCngobj.HashAlgorithm = CngAlgorithm.Sha256; byte[] _myPublicKey = ECDiffieHellmanCngobj.PublicKey.ToByteArray(); byte[] _otherPublicKey = new byte[140]; if (NetworkCommunicationManagers.SendByteArrayOverSocket(socket, _myPublicKey) == false) { return(null); } ; if (NetworkCommunicationManagers.ReceiveByteArrayOverSocket(socket, out _otherPublicKey, 140) == false) { return(null); } ; return(ECDiffieHellmanCngobj.DeriveKeyMaterial(CngKey.Import(_otherPublicKey, CngKeyBlobFormat.EccPublicBlob))); } }
private static void BobReceivesData(byte[] encryptedData) { Console.WriteLine("Bob receives encrpyted data"); byte[] rawData = null; AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) { iv[i] = encryptedData[i]; } ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(bobKey); using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine("Bob creates this key with Alices public key information: {0}", Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); Console.WriteLine("Bob decrypts message to: {0}", Encoding.UTF8.GetString(rawData)); } aes.Clear(); } }
public static void KeyUret() { using (ECDiffieHellmanCng ecd1 = new ECDiffieHellmanCng()) { ecd1.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ecd1.HashAlgorithm = CngAlgorithm.Sha256; kullanici_1_Pulic_Key = ecd1.PublicKey.ToByteArray(); txt_Kul_1_Public_Key = Convert.ToBase64String(kullanici_1_Pulic_Key); using (ECDiffieHellmanCng ecd2 = new ECDiffieHellmanCng()) { ecd2.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ecd2.HashAlgorithm = CngAlgorithm.Sha256; kullanici_2_Pulic_Key = ecd2.PublicKey.ToByteArray(); txt_Kul_2_Public_Key = Convert.ToBase64String(kullanici_2_Pulic_Key); ortak_Anahtar = ecd2.DeriveKeyMaterial(CngKey.Import(kullanici_1_Pulic_Key, CngKeyBlobFormat.EccPublicBlob)); txt_Ortak_Anahtar = Convert.ToBase64String(ortak_Anahtar); } } }
private async Task <byte[]> AliceSendsDataAsync(string message) { WriteLine($"Alice sends message: {message}"); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey)) using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); WriteLine("Alice creates this symmetric key with " + $"Bobs public key information: { Convert.ToBase64String(symmKey)}"); using (var aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (var ms = new MemoryStream()) { // create CryptoStream and encrypt data to send using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { // write initialization vector not encrypted await ms.WriteAsync(aes.IV, 0, aes.IV.Length); await cs.WriteAsync(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } aes.Clear(); } } WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}");; WriteLine(); return(encryptedData); }
private void GenerateKeys() { using (ECDiffieHellmanCng ecd1 = new ECDiffieHellmanCng()) { ecd1.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ecd1.HashAlgorithm = CngAlgorithm.Sha256; person1PublicKey = ecd1.PublicKey.ToByteArray(); txt_Kul_1_Public_Key.Text = Convert.ToBase64String(person1PublicKey); /* 2. kişi tarafındaki işlemler, 1. kişinin açık anahtarı biliniyor. */ using (ECDiffieHellmanCng ecd2 = new ECDiffieHellmanCng()) { ecd2.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ecd2.HashAlgorithm = CngAlgorithm.Sha256; person2PublicKey = ecd2.PublicKey.ToByteArray(); txt_Kul_2_Public_Key.Text = Convert.ToBase64String(person2PublicKey); commonKey = ecd2.DeriveKeyMaterial(CngKey.Import(person1PublicKey, CngKeyBlobFormat.EccPublicBlob)); txt_Ortak_Anahtar.Text = Convert.ToBase64String(commonKey); } } }
/// <summary> /// 加密 /// </summary> /// <param name="message"></param> /// <returns></returns> private async Task <byte[]> AliceSendsDataAsync(string message) { Console.WriteLine("Alice sends message:" + message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; //创建ECDiffieHellmanCng对象,并使用Alice的密钥对初始化它 using (ECDiffieHellmanCng aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey)) using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { //使用Alice的密钥对和Bob的公钥创建一个对称密钥,返回的对称密钥使用对称算法AES加密数据 byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice creates thsi symmetric key with Bobs public key Information:" + Convert.ToBase64String(symmKey)); // using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { await ms.WriteAsync(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } //在访问内存流中的加密数据之前,必须关闭加密流,否则加密数据就会丢失最后的位 aes.Clear(); } } Console.WriteLine("Alice:message is encrypted:" + Convert.ToBase64String(encryptedData)); Console.WriteLine(); return(encryptedData); }
private void Listen() { if (Proxy == null) { Proxy = new Publisher(PrivateSpace, Space, ConcealedSpace); } Proxy.Running = true; while (true) { var request = Space.Get("Request", typeof(HubRequestType), typeof(string), typeof(string)); var identifier = request.Get <string>(2); var requestType = request.Get <HubRequestType>(1); var secret = request.Get <string>(3); if (requestType == HubRequestType.EstablishSession) { var t = PrivateSpace.QueryP("SessionSecret", typeof(string), identifier); if (t != null) { PrivateSpace.GetAll("SessionSecret", typeof(string), identifier); } using (var me = new ECDiffieHellmanCng()) { var herKey = CngKey.Import(Convert.FromBase64String(secret), CngKeyBlobFormat.EccPublicBlob); var ourKey = Convert.ToBase64String(me.DeriveKeyMaterial(herKey)); PrivateSpace.Put("SessionSecret", ourKey, identifier); var myKey = Convert.ToBase64String(me.PublicKey.ToByteArray()); Space.Put("Response", identifier, HubRequestType.EstablishSession, myKey); } Proxy.SyncIncomingUser(identifier); } else if (requestType == HubRequestType.TerminateSession) { PrivateSpace.GetP("SessionSecret", typeof(string), identifier); } } }
private void BeginEncrypting(ref sClient sC) { byte[] sSymKey; CngKey sCngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); byte[] sPublic = sCngKey.Export(CngKeyBlobFormat.EccPublicBlob); BlockingSend(sC, Headers.HEADER_HANDSHAKE, sPublic); object[] oRecv = BlockingReceive(sC); if (!oRecv[0].Equals(Headers.HEADER_HANDSHAKE)) { sC.cSocket.Disconnect(true); } byte[] cBuf = oRecv[1] as byte[]; using (var sAlgo = new ECDiffieHellmanCng(sCngKey)) using (CngKey cPubKey = CngKey.Import(cBuf, CngKeyBlobFormat.EccPublicBlob)) sSymKey = sAlgo.DeriveKeyMaterial(cPubKey); sC.eCls = new Encryption(sSymKey, HASH_STRENGTH.MINIMAL); }
/// <summary> /// 解密 /// </summary> /// <param name="encrytpedData"></param> /// <returns></returns> private async Task BobReceivesDataAsync(byte[] encrytpedData) { Console.WriteLine("Bob receives encrypted data"); byte[] rawData = null; //读取未加密的初始化矢量 AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); //BlockSize属性返回块的位数,除以8就可以计算出字节数。 int nBytes = aes.BlockSize / 8; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) { iv[i] = encrytpedData[i]; } //实例化一个ECDiffieHellmanCng对象,使用Alice的公钥,从DeriveKeyMaterial()方法中返回对称密钥 using (ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(_bobKey)) using (CngKey alicePubKey = CngKey.Import(_alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); Console.WriteLine("Bob creates this symmetric key with Alices public key information:" + Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write)) { await cs.WriteAsync(encrytpedData, nBytes, encrytpedData.Length - nBytes); } rawData = ms.ToArray(); Console.WriteLine("Bob decrypts mesage to:" + Encoding.UTF8.GetString(rawData)); } aes.Clear(); } }
public static EncryptionResult Encrypt(byte[] userKey, byte[] userSecret, byte[] payload //, ushort padding = 0, bool randomisePadding = false // not implemented yet ) { var salt = GenerateSalt(16); byte[] serverPublicKey = null; byte[] key = null; var cgnKey = ImportCngKeyFromPublicKey(userKey); using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng(256)) { alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hmac; alice.HashAlgorithm = CngAlgorithm.Sha256; alice.HmacKey = userSecret; serverPublicKey = ImportPublicKeyFromCngKey(alice.PublicKey.ToByteArray()); key = alice.DeriveKeyMaterial(cgnKey); } var prk = HKDFSecondStep(key, Encoding.UTF8.GetBytes("Content-Encoding: auth\0"), 32); byte[] cek = HKDF(salt, prk, CreateInfoChunk("aesgcm", userKey, serverPublicKey), 16); byte[] nonce = HKDF(salt, prk, CreateInfoChunk("nonce", userKey, serverPublicKey), 12); var input = AddPaddingToInput(payload); var encryptedMessage = EncryptAes(nonce, cek, input); return(new EncryptionResult { Salt = salt, Payload = encryptedMessage, PublicKey = serverPublicKey }); }
static void KeysExchenge() { byte[] inputBuffer = new byte[1024]; Stream inputStream = Console.OpenStandardInput(inputBuffer.Length); Console.SetIn(new StreamReader(inputStream, Console.InputEncoding, false, inputBuffer.Length)); byte[] OurPublicKey; byte[] TheirPublicKey; using (var ec = new ECDiffieHellmanCng()) { ec.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; ec.HashAlgorithm = CngAlgorithm.Sha256; OurPublicKey = ec.PublicKey.ToByteArray(); Console.WriteLine("Our public key: {0}", BitConverter.ToString(OurPublicKey).Replace("-", "").ToLowerInvariant()); Console.Write("Input their public key:"); string str = Console.ReadLine(); TheirPublicKey = StringToByteArray(str); byte[] sendKey = ec.DeriveKeyMaterial(CngKey.Import(TheirPublicKey, CngKeyBlobFormat.EccPublicBlob)); Console.WriteLine("Our secret key: {0}", BitConverter.ToString(OurPublicKey).Replace("-", "").ToLowerInvariant()); } }
internal void DeriveKey(string otherPartyPublicKey) { aes = new RijndaelManaged(); aes.Padding = PaddingMode.PKCS7; try { byte[] aesBytes = dh.DeriveKeyMaterial(ECDiffieHellmanCngPublicKey.FromXmlString(otherPartyPublicKey)); for (int i = 0; i < aes.Key.Length; ++i) { aes.Key[i] = aesBytes[i]; } for (int i = 0; i < aes.IV.Length; ++i) { aes.IV[i] = aesBytes[i]; } } catch (Exception) { aes = null; throw; } }