调用openssl的sm2
时间: 2023-11-08 13:59:14 浏览: 111
要调用openssl的sm2算法,可以通过在openssl中嵌入相应接口来实现。从openssl 1.1.1版本开始,已经提供了对国密SM2算法的支持。在openssl的源码中的crypto/include/internal目录下有sm2, sm3, sm4的设计实现。但是直接调用这些实现是无法实现国密SM2算法的加解密的。需要通过openssl的evp接口来实现国密SM2算法的加解密。
相关问题
openssl sm2
在OpenSSL中,通过使用EVP接口可以实现对国密SM2算法的加解密。可以在OpenSSL的源码中的crypto/include/internall目录下找到sm2、sm3和sm4的设计实现,但无法直接调用。为了使用国密SM2算法,需要将原始的私钥文件转换为pkcs8格式。可以使用以下命令将私钥文件转换为pkcs8格式:openssl pkcs8 -topk8 -inform PEM -in ec_param.pem -outform pem -nocrypt -out pri_key_pkcs8.pem。这样就可以通过OpenSSL的EVP接口进行国密SM2算法的加解密操作了。
openssl sm2加解密C语言调用
以下是 OpenSSL 库中使用 SM2 算法进行加解密的示例代码:
```c
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/sm2.h>
void sm2_encrypt_decrypt_example()
{
EVP_PKEY* pkey = NULL;
EC_KEY* ec_key = NULL;
unsigned char* plaintext = (unsigned char*)"test";
unsigned char ciphertext[1024] = {0};
int ciphertext_len = 0;
unsigned char decryptedtext[1024] = {0};
int decryptedtext_len = 0;
EVP_MD_CTX* mdctx = NULL;
// 生成 SM2 密钥对
ec_key = EC_KEY_new_by_curve_name(NID_sm2);
if (ec_key == NULL)
{
goto cleanup;
}
if (!EC_KEY_generate_key(ec_key))
{
goto cleanup;
}
pkey = EVP_PKEY_new();
if (pkey == NULL)
{
goto cleanup;
}
if (!EVP_PKEY_set1_EC_KEY(pkey, ec_key))
{
goto cleanup;
}
// 加密
mdctx = EVP_MD_CTX_new();
if (mdctx == NULL)
{
goto cleanup;
}
if (!EVP_PKEY_encrypt_init(mdctx))
{
goto cleanup;
}
if (!EVP_PKEY_CTX_set_ec_scheme(mdctx->pkey_ctx, NID_sm_scheme))
{
goto cleanup;
}
if (!EVP_PKEY_CTX_set_ec_encrypt_md(mdctx->pkey_ctx, EVP_sm3()))
{
goto cleanup;
}
if (!EVP_PKEY_CTX_set_ec_key(mdctx->pkey_ctx, ec_key))
{
goto cleanup;
}
if (!EVP_PKEY_encrypt(mdctx, ciphertext, &ciphertext_len, plaintext, strlen((char*)plaintext)))
{
goto cleanup;
}
// 解密
if (!EVP_PKEY_decrypt_init(mdctx))
{
goto cleanup;
}
if (!EVP_PKEY_CTX_set_ec_scheme(mdctx->pkey_ctx, NID_sm_scheme))
{
goto cleanup;
}
if (!EVP_PKEY_CTX_set_ec_decrypt_md(mdctx->pkey_ctx, EVP_sm3()))
{
goto cleanup;
}
if (!EVP_PKEY_CTX_set_ec_key(mdctx->pkey_ctx, ec_key))
{
goto cleanup;
}
if (!EVP_PKEY_decrypt(mdctx, decryptedtext, &decryptedtext_len, ciphertext, ciphertext_len))
{
goto cleanup;
}
printf("Decrypted text is: %s\n", decryptedtext);
cleanup:
if (mdctx != NULL)
{
EVP_MD_CTX_free(mdctx);
}
if (pkey != NULL)
{
EVP_PKEY_free(pkey);
}
if (ec_key != NULL)
{
EC_KEY_free(ec_key);
}
}
```
该示例代码中使用了 OpenSSL 库中的 `EVP_PKEY_encrypt()` 和 `EVP_PKEY_decrypt()` 函数进行加解密操作。SM2 算法的相关参数通过 `EVP_PKEY_CTX_set_ec_scheme()` 和 `EVP_PKEY_CTX_set_ec_encrypt_md()` 等函数设置。请注意,此示例代码仅作为参考,具体实现可能需要根据应用场景进行调整。