我在使用ECDiffieHellmanCng类交换密钥时遇到问题:
第 1 步 - 创建公钥
public byte[] CreatePublicKey()
{
using (ECDiffieHellmanCng cng = new ECDiffieHellmanCng())
{
cng.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
cng.HashAlgorithm = CngAlgorithm.Sha512;
return cng.PublicKey.ToByteArray();
}
}
第 2 步 - 交换并获取私钥
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));
}
}
例子
byte[] alicePublicKey = CreatePublicKey();
byte[] bobPublicKey = CreatePublicKey();
// This fails
byte[] alicePrivateKey = CreatePrivateKey(alicePublicKey, bobPublicKey);
byte[] bobPrivateKey = CreatePrivateKey(bobPublicKey, alicePublicKey);
具体来说,它在该方法的这一行失败CreatePrivateKey(...)
:
return cng.DeriveKeyMaterial(CngKey.Import(publicKey2, CngKeyBlobFormat.EccPublicBlob));
错误
System.Security.Cryptography.CryptographicException:“密钥不存在。”
我究竟做错了什么?