I'm having trouble exchanging keys using the ECDiffieHellmanCng class:
Step 1 - Create a public key
public byte[] CreatePublicKey()
{
using (ECDiffieHellmanCng cng = new ECDiffieHellmanCng())
{
cng.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
cng.HashAlgorithm = CngAlgorithm.Sha512;
return cng.PublicKey.ToByteArray();
}
}
Step 2 - Exchange and get private key
public byte[] CreatePrivateKey(byte[] publicKey1, byte[] publicKey2)
{
using(ECDiffieHellmanCng cng = new ECDiffieHellmanCng(CngKey.Import(publicKey1, CngKeyBlobFormat.EccPublicBlob)))
{
cng.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
cng.HashAlgorithm = CngAlgorithm.Sha512;
return cng.DeriveKeyMaterial(CngKey.Import(publicKey2, CngKeyBlobFormat.EccPublicBlob));
}
}
Example
byte[] alicePublicKey = CreatePublicKey();
byte[] bobPublicKey = CreatePublicKey();
// This fails
byte[] alicePrivateKey = CreatePrivateKey(alicePublicKey, bobPublicKey);
byte[] bobPrivateKey = CreatePrivateKey(bobPublicKey, alicePublicKey);
Specifically it fails on this line from the CreatePrivateKey(...)
method:
return cng.DeriveKeyMaterial(CngKey.Import(publicKey2, CngKeyBlobFormat.EccPublicBlob));
Error
System.Security.Cryptography.CryptographicException: 'Key does not exist.'
What am I doing wrong?