上面的实现似乎太复杂了。openssl/evp.h
具有函数i2d_PublicKey()
并d2i_PublicKey()
分别转换为公钥的二进制表示和从公钥的二进制表示转换(并且私钥有等效的函数 - 参见:https ://www.openssl.org/docs/manmaster/man3/d2i_PublicKey.html )
一个小代码示例:
vector<unsigned char> ecdhPubkeyData(EVP_PKEY *key)
{
int len = i2d_PublicKey(key, 0); // with 0 as second arg it gives length
vector<unsigned char> ret(len);
unsigned char *ptr = ret.data();
len = i2d_PublicKey(key, &ptr);
return ret;
}
// Make sure you free the returned pointer when you are done with it
EVP_PKEY *ecdhPubkeyFromData(vector <unsigned char> const &pubkeyData)
{ // You do need to put in in an existing EVP_PKEY that is assigned
// an EC_KEY, because it needs to know what curve you use
EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
EVP_PKEY *ret = EVP_PKEY_new();
EVP_PKEY_assign_EC_KEY(ret, ec_key);
unsigned char const *ptr = pubkeyData.data();
d2i_PublicKey(EVP_PKEY_EC, &ret, &ptr, pubkeyData.size());
return ret;
}
// PS: In a real example you want to check if any of these functions
// return NULL or some error code
我正在使用 C++ 向量来包含二进制数据,但当然你也可以使用 C 风格的数组 :-)
我绝对不是 OpenSSL 专家,所以如果我在这个实现中做错了什么,请告诉我:-p