OpenSSL在使用X25519时的小坑

来源:互联网 发布:linux ping命令 编辑:程序博客网 时间:2024/06/06 04:33

OpenSSL从v1.1.0开始,就支持椭圆曲线密钥交换(ECDH)使用X25519曲线。

而OpenSSL里生成EC密钥对的示例程序大致是这样的:

EVP_PKEY_CTX *pctx, *kctx;EVP_PKEY *pkey = NULL, *params = NULL;/* Create the context for parameter generation */if(NULL == (pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))) handleErrors();/* Initialise the parameter generation */if(1 != EVP_PKEY_paramgen_init(pctx)) handleErrors();/* We're going to use the ANSI X9.62 Prime 256v1 curve */if(1 != EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1)) handleErrors();/* Create the parameter object params */if (!EVP_PKEY_paramgen(pctx, &params)) handleErrors();/* Create the context for the key generation */if(NULL == (kctx = EVP_PKEY_CTX_new(params, NULL))) handleErrors();/* Generate the key */if(1 != EVP_PKEY_keygen_init(kctx)) handleErrors();if (1 != EVP_PKEY_keygen(kctx, &pkey)) handleErrors();

但是当你想把曲线从prime256v1改成X25519时,问题就出现了,OpenSSL会提示unknown group。乍一看好像OpenSSL并不支持X25519。

其实只是X25519曲线的使用方式和其它曲线有点不太一样:

EVP_PKEY_CTX *pctx;EVP_PKEY *pkey= NULL;/* Create the context for parameter generation */if (NULL == (pctx = EVP_PKEY_CTX_new_id(NID_X25519, NULL))) handleErrors();/* Generate the key */if (1 != EVP_PKEY_keygen_init(pctx)) handleErrors();if (1 != EVP_PKEY_keygen(pctx, &pkey) handleErrors();