如果使用自定义素数和生成器,则必须创建域参数为first的EVP_PKEY.
// Create the OSSL_PARAM_BLD.
OSSL_PARAM_BLD* paramBuild = OSSL_PARAM_BLD_new();
if (!paramBuild) {
// report the error
}
// Set the prime and generator.
if (!OSSL_PARAM_BLD_push_BN(paramBuild, OSSL_PKEY_PARAM_FFC_P, prime) ||
!OSSL_PARAM_BLD_push_BN(paramBuild, OSSL_PKEY_PARAM_FFC_G, generator)) {
// report the error
}
// Convert to OSSL_PARAM.
OSSL_PARAM* param = OSSL_PARAM_BLD_to_param(paramBuild);
if (!param) {
// report the error
}
// Create the context. The name is DHX not DH!!!
EVP_PKEY_CTX* domainParamKeyCtx = EVP_PKEY_CTX_new_from_name(nullptr, "DHX", nullptr);
if (!domainParamKeyCtx) {
// report the error
}
// Initialize the context.
if (EVP_PKEY_fromdata_init(domainParamKeyCtx) <= 0) {
// report the error
}
// Create the domain parameter key.
EVP_PKEY* domainParamKey = nullptr;
if (EVP_PKEY_fromdata(domainParamKeyCtx, &domainParamKey,
EVP_PKEY_KEY_PARAMETERS, param) <= 0) {
// report the error
}
域参数domainParamKey准备好了!现在,使用它来创建密钥对.
EVP_PKEY_CTX* keyGenerationCtx = EVP_PKEY_CTX_new_from_pkey(nullptr, domainParamKey, nullptr);
if (!keyGenCtx) {
// report the error
}
if (EVP_PKEY_keygen_init(keyGenerationCtx) <= 0) {
// report the error
}
EVP_PKEY* keyPair = nullptr;
if (EVP_PKEY_generate(keyGenerationCtx, &keyPair) <= 0) {
// report the error
}
keys 对keyPair准备好了!
在GitHub上查看这个项目:https://github.com/eugen15/diffie-hellman-cpp.它展示了如何生成密钥对,设置和获取Diffie-Hellman参数.此外,它还有一些定制的Diffie-Hellman实现.
有关OpenSSL 3示例,请参见以下文件:
- diffie-hellman-openssl.h
- diffie-hellman-openssl.cpp
以下文件是一个LibreSSL示例,基本上是版本3之前的OpenSSL.这是为了确保您具有向后兼容性.
- diffie-hellman-libressl-dh.h
- diffie-hellman-libressl-dh.cpp
More things to consider
FIRST
如果在OpenSSL 3之前使用自定义素数,那么最好使用预定义的安全素数.你可以在这里看到一个例子:https://www.openssl.org/docs/manmaster/man7/EVP_PKEY-DH.html
int priv_len = 2 * 112;
OSSL_PARAM params[3];
EVP_PKEY *pkey = NULL;
EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_from_name(NULL, "DH", NULL);
params[0] = OSSL_PARAM_construct_utf8_string("group", "ffdhe2048", 0);
/* "priv_len" is optional */
params[1] = OSSL_PARAM_construct_int("priv_len", &priv_len);
params[2] = OSSL_PARAM_construct_end();
EVP_PKEY_keygen_init(pctx);
EVP_PKEY_CTX_set_params(pctx, params);
EVP_PKEY_generate(pctx, &pkey);
...
EVP_PKEY_free(pkey);
EVP_PKEY_CTX_free(pctx);
Alice执行上述代码(摘自OpenSSL手册).然后得到素数和生成器:
EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_FFC_P, &prime);
EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_FFC_G, &generator);
然后将其发送到Bob,并使用上面的代码创建密钥对.
SECOND
在新项目中使用椭圆曲线Diffie-Hellman(ECDH)密钥交换.速度要快得多.把你的DH作为备用方案.我将很快为github项目添加一些示例代码.