public static void RunECDHE(int iterations) { Console.WriteLine("Running " + iterations + " diffie hellman key exchanges"); Stopwatch watch = new Stopwatch(); for (int i = 0; i < iterations; i++) { watch.Start(); // Both create their instances ECDiffieHellman serverDiffie = new ECDiffieHellman(); ECDiffieHellman clientDiffie = new ECDiffieHellman(); // Exchange publics /* START TRANSMISSION */ byte[] serverPublic = serverDiffie.GetPublicKey(); byte[] clientPublic = clientDiffie.GetPublicKey(); /* END TRANSMISSION */ // Calculate shared byte[] key1 = serverDiffie.GetSharedSecretRaw(clientPublic); byte[] key2 = clientDiffie.GetSharedSecretRaw(serverPublic); watch.Stop(); if (key1.Length != key2.Length) { Console.WriteLine("CRITICAL: LENGTH MISSMATCH"); continue; } for (int x = 0; x < key1.Length; x++) { if (key1[x] != key2[x]) { Console.WriteLine("CRITICAL: MISSMATCH"); break; } } } Console.WriteLine("Completed in " + watch.ElapsedMilliseconds + " ms, " + (watch.ElapsedMilliseconds / iterations) + " ms per exchange"); }
public byte[] GetSecurePublicPart() { byte[] publicPart = _diffieHellanInstance.GetPublicKey(); using (SHA256Managed sha = new SHA256Managed()) { byte[] proofPart; if (_isSigner) { // Sign the hash with the private key proofPart = _rsa.SignData(publicPart, sha); } else { // Encrypt the public part with the opposite public proofPart = _rsa.Encrypt(sha.ComputeHash(publicPart), false); } // Final has two lengths appended byte[] final = new byte[(sizeof(ushort) * 2) + publicPart.Length + proofPart.Length]; // Write lengths to final for (byte i = 0; i < sizeof(ushort); i++) { final[i] = ((byte)(publicPart.Length >> (i * 8))); } for (byte i = 0; i < sizeof(ushort); i++) { final[i + sizeof(ushort)] = ((byte)(proofPart.Length >> (i * 8))); } // Copy parts Buffer.BlockCopy(publicPart, 0, final, (sizeof(ushort) * 2), publicPart.Length); Buffer.BlockCopy(proofPart, 0, final, (sizeof(ushort) * 2) + publicPart.Length, proofPart.Length); return(final); } }