openssl使用SM2进行数据加密和数据解密

发布于:2025-09-01 ⋅ 阅读:(19) ⋅ 点赞:(0)

一、准备工作

1. 安装依赖

sudo apt-get update
sudo apt-get install libssl-dev

2. 确认 OpenSSL 版本

openssl version

如果是 1.1.13.0+,就支持 SM2/SM3/SM4


二、C 语言示例代码

这个程序会:

  1. 生成 SM2 密钥对
  2. 使用公钥加密一段明文
  3. 使用私钥解密恢复明文
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/sm2.h>
#include <openssl/pem.h>

int main() {
    EVP_PKEY_CTX *pctx = NULL;
    EVP_PKEY *pkey = NULL;

    // ========== 1. 生成 SM2 密钥对 ==========
    pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL);
    if (!pctx) {
        printf("EVP_PKEY_CTX_new_id failed\n");
        return -1;
    }

    if (EVP_PKEY_keygen_init(pctx) <= 0) {
        printf("EVP_PKEY_keygen_init failed\n");
        return -1;
    }

    if (EVP_PKEY_keygen(pctx, &pkey) <= 0) {
        printf("EVP_PKEY_keygen failed\n");
        return -1;
    }
    EVP_PKEY_CTX_free(pctx);

    printf("SM2 KeyPair generated successfully!\n");

    // ========== 2. 加密 ==========
    const char *plaintext = "Hello, SM2 Encryption!";
    size_t plaintext_len = strlen(plaintext);

    size_t ciphertext_len = 0;
    unsigned char *ciphertext = NULL;

    if (!SM2_encrypt(EVP_sm3(), (const unsigned char*)plaintext, plaintext_len,
                     NULL, &ciphertext_len, pkey)) {
        printf("SM2_encrypt (get length) failed\n");
        return -1;
    }

    ciphertext = OPENSSL_malloc(ciphertext_len);
    if (!ciphertext) {
        printf("malloc failed\n");
        return -1;
    }

    if (!SM2_encrypt(EVP_sm3(), (const unsigned char*)plaintext, plaintext_len,
                     ciphertext, &ciphertext_len, pkey)) {
        printf("SM2_encrypt failed\n");
        return -1;
    }

    printf("Ciphertext length = %zu\n", ciphertext_len);

    // ========== 3. 解密 ==========
    unsigned char *decrypted = OPENSSL_malloc(ciphertext_len);
    size_t decrypted_len = 0;

    if (!SM2_decrypt(EVP_sm3(), ciphertext, ciphertext_len,
                     decrypted, &decrypted_len, pkey)) {
        printf("SM2_decrypt failed\n");
        return -1;
    }

    decrypted[decrypted_len] = '\0'; // 末尾加字符串结束符
    printf("Decrypted text: %s\n", decrypted);

    // ========== 4. 释放资源 ==========
    OPENSSL_free(ciphertext);
    OPENSSL_free(decrypted);
    EVP_PKEY_free(pkey);

    return 0;
}

三、编译与运行

1. 编译

gcc sm2_enc_dec.c -o sm2_enc_dec -lcrypto

2. 运行

./sm2_enc_dec

3. 可能的输出

SM2 KeyPair generated successfully!
Ciphertext length = 115
Decrypted text: Hello, SM2 Encryption!

四、总结

  • EVP_PKEY_keygen() 生成 SM2 密钥对
  • SM2_encrypt() 使用公钥加密
  • SM2_decrypt() 使用私钥解密
  • 这里默认使用 SM3 作为哈希函数(推荐国密组合:SM2+SM3+SM4)


网站公告

今日签到

点亮在社区的每一天
去签到