我想使用 Diffie hellman 在 ac# Server 和 c++ Client 之间生成密钥。此代码为服务器生成一个公钥:
serverECDH = new ECDiffieHellmanCng(ECCurve.NamedCurves.nistP256);
serverECDH.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
serverECDH.HashAlgorithm = CngAlgorithm.Sha256;
ECDHPublicKey =Convert.ToBase64String(serverECDH.PublicKey.ToByteArray());
Console.WriteLine(serverECDH.KeySize); //256
Console.WriteLine(serverECDH.PublicKey.ToByteArray().Length); //72
Console.WriteLine(ECDHPublicKey);
我想知道为什么 publicKey 字节数组大小是 72 而我期望一个 64 字节长的数组?除此之外,这是我在客户端生成公钥的实现:
if (NULL == (pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))) HandleErrors(1);
if (1 != EVP_PKEY_paramgen_init(pctx)) HandleErrors(2);
if (1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1)) HandleErrors(3);
if (!EVP_PKEY_paramgen(pctx, ¶ms)) HandleErrors(4);
if (NULL == (kctx = EVP_PKEY_CTX_new(params, NULL))) HandleErrors(5);
if (1 != EVP_PKEY_keygen_init(kctx)) HandleErrors(6);
if (1 != EVP_PKEY_keygen(kctx, &pkey)) HandleErrors(7);
bio = BIO_new(BIO_s_mem());
PEM_write_bio_PUBKEY(bio, pkey);
int publicKeyLen = BIO_pending(bio);
cout << publicKeyLen << endl;
unsigned char* publicKeyChar = (unsigned char*)malloc(publicKeyLen);
BIO_read(bio, publicKeyChar, publicKeyLen);
ECDHPublicKey = string(reinterpret_cast<char const*>(publicKeyChar),publicKeyLen);
cout << ECDHPublicKey << endl;
在这段代码中,公钥长度为 128 字节(字符?),这又是奇数,因为我指定了 NID_X9_62_prime256v1 曲线。我的错误在哪里?除了 C++ 和 C# 中的 NID_X9_62_prime256v1 和 nistP256 匹配吗?
编辑:这是 cout << ECDHPublicKey << endl output 的示例:
-----开始公钥----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEUFD9ZNby6x2bf/VC16/NHSxIXdit Ips60uLoi0/jKmbmMHRg2xbXVVzV8Uc1DElMlZA817bMFCnVvi1VsM5JYg==
-----结束公钥-----