Compute SM2 encryption and decryption by invoking EVP interface in OpenSSL 1.1.1

    How to compute SM2 signature and verify it is introduced in the previous article. In this post a demo of performing SM2 encryption and decryption by invoking EVP interface in OpenSSL 1.1.1 is provided:

/**************************************************
* File name: EVP_sm2_encrypt_and_decrypt.c
* Author: HAN Wei
* Author's blog: https://blog.csdn.net/henter/
* Date: May 1st, 2020
* Description: demonstrate how to compute SM2 encryption
	   and decryption by invoking EVP interface
	   in OpenSSL 1.1.1
**************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "openssl/ec.h"
#include "openssl/evp.h"

/**************************************************
* Main function return value:
	0:   main function executes successfully
	-1:  an error occurs
**************************************************/
int main(void)
{
	int ret = -1, i;
	EVP_PKEY_CTX *pctx = NULL, *ectx = NULL;
	EVP_PKEY *pkey = NULL;
	unsigned char message[16] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,
				  0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
	size_t message_len = sizeof(message);
	unsigned char *ciphertext = NULL, *plaintext = NULL;
	size_t ciphertext_len, plaintext_len;
	EC_KEY *key_pair = NULL;
	const BIGNUM *priv_key = NULL;
	char *priv_key_str = NULL;

	const EC_GROUP *group = NULL;
	const EC_POINT *pub_key = NULL;
	BN_CTX *ctx = NULL;
	BIGNUM *x_coordinate = NULL, *y_coordinate = NULL;
	char *x_coordinate_str = NULL, *y_coordinate_str = NULL;

/* create SM2 Ellipse Curve parameters and key pair */
	if ( !(pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL)) )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_paramgen_init(pctx)) != 1 )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_sm2)) <= 0 )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_keygen_init(pctx)) != 1 )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_keygen(pctx, &pkey)) != 1 )
	{
		goto clean_up;
	}

/* print SM2 key pair */
	if ( !(key_pair = EVP_PKEY_get0_EC_KEY(pkey)) )
	{
		goto clean_up;
	}

	if ( !(priv_key = EC_KEY_get0_private_key(key_pair)) )
	{
		goto clean_up;
	}

	if ( !(priv_key_str = BN_bn2hex(priv_key)) )
	{
		goto clean_up;
	}
	printf("SM2 private key (in hex form):\n");
	printf("%s\n\n", priv_key_str);

	if ( !(pub_key = EC_KEY_get0_public_key(key_pair)) )
	{
		goto clean_up;
	}

	if ( !(group = EC_KEY_get0_group(key_pair)) )
	{
		goto clean_up;
	}

	if ( !(ctx = BN_CTX_new()) )
	{
		goto clean_up;
	}
	BN_CTX_start(ctx);
	x_coordinate = BN_CTX_get(ctx);
	y_coordinate = BN_CTX_get(ctx);
	if ( !(y_coordinate) )
	{
		goto clean_up;
	}
	if ( !(EC_POINT_get_affine_coordinates(group, pub_key, x_coordinate, y_coordinate, ctx)) )
	{
		goto clean_up;
	}
	if ( !(x_coordinate_str = BN_bn2hex(x_coordinate)) )
	{
		goto clean_up;
	}
	printf("x coordinate in SM2 public key (in hex form):\n");
	printf("%s\n\n", x_coordinate_str);

	if ( !(y_coordinate_str = BN_bn2hex(y_coordinate)) )
	{
		goto clean_up;
	}
	printf("y coordinate in SM2 public key (in hex form):\n");
	printf("%s\n\n", y_coordinate_str);

/* compute SM2 encryption */
	if ( (EVP_PKEY_set_alias_type(pkey, EVP_PKEY_SM2)) != 1 )
	{
		goto clean_up;
	}

	if ( !(ectx = EVP_PKEY_CTX_new(pkey, NULL)) )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_encrypt_init(ectx)) != 1 )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_encrypt(ectx, NULL, &ciphertext_len, message, message_len)) != 1 )
	{
		goto clean_up;
	}

	if ( !(ciphertext = (unsigned char *)malloc(ciphertext_len)) )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_encrypt(ectx, ciphertext, &ciphertext_len, message, message_len)) != 1 )
	{
		goto clean_up;
	}

	printf("Message length: %d bytes.\n", message_len);
	printf("Message:\n");
	for (i = 0; i < (int)message_len; i++)
	{
		printf("0x%x  ", message[i]);
	}
	printf("\n\n");

	printf("Ciphertext length: %d bytes.\n", ciphertext_len);
	printf("Ciphertext (ASN.1 encode):\n");
	for (i = 0; i < (int)ciphertext_len; i++)
	{
		printf("0x%x  ", ciphertext[i]);
	}
	printf("\n\n");

/* compute SM2 decryption */
	if ( (EVP_PKEY_decrypt_init(ectx)) != 1 )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_decrypt(ectx, NULL, &plaintext_len, ciphertext, ciphertext_len)) != 1 )
	{
		goto clean_up;
	}

	if ( !(plaintext = (unsigned char *)malloc(plaintext_len)) )
	{
		goto clean_up;
	}

	if ( (EVP_PKEY_decrypt(ectx, plaintext, &plaintext_len, ciphertext, ciphertext_len)) != 1 )
	{
		goto clean_up;
	}

	printf("Decrypted plaintext length: %d bytes.\n", plaintext_len);
	printf("Decrypted plaintext:\n");
	for (i = 0; i < (int)plaintext_len; i++)
	{
		printf("0x%x  ", plaintext[i]);
	}
	printf("\n\n");

	if ( plaintext_len != message_len )
	{
		printf("Decrypted data length error!\n");
		goto clean_up;
	}

	if ( memcmp(plaintext, message, message_len) )
	{
		printf("Decrypt data failed!\n");
		goto clean_up;
	}
	else
	{
		printf("Encrypt and decrypt data succeeded!\n");
	}

	ret = 0;
clean_up:
	if (pctx)
	{
		EVP_PKEY_CTX_free(pctx);
	}

	if (pkey)
	{
		EVP_PKEY_free(pkey);
	}

	if (priv_key_str)
	{
		OPENSSL_free(priv_key_str);
	}

	if (ctx)
	{
		BN_CTX_end(ctx);
		BN_CTX_free(ctx);
	}

	if (x_coordinate_str)
	{
		OPENSSL_free(x_coordinate_str);
	}

	if (y_coordinate_str)
	{
		OPENSSL_free(y_coordinate_str);
	}

	if (ectx)
	{
		EVP_PKEY_CTX_free(ectx);
	}

	if (ciphertext)
	{
		free(ciphertext);
	}

	if (plaintext)
	{
		free(plaintext);
	}

#if defined(_WIN32) || defined(_WIN64)
	system("pause");
#endif
	return ret;
}

    The result is as below:

SM2算法是由中国国家密码管理局研究所设计的一种公钥密码算法,与国际上使用广泛的RSA和ECC算法不同,SM2算法采用了国密体系所定义的椭圆曲线密码体系,并加入了大量的安全机制,使得它在国内文化背景下具有很高的安全性和可靠性。 在SM2算法中,sm2_compute_id_digest函数是用于计算消息摘要的函数。它采用了国密体系中定义的哈希算法,将原始消息转化为一个长度为256位的固定长度摘要。sm2_compute_id_digest函数的具体实现步骤如下: 1. 读入输入的消息数据,计算数据的长度,以便于之后的拼接和填充操作。 2. 采用SM3哈希算法对输入消息进行处理,并将处理结果保存在buf1缓冲区中。 3. 用掩码随机化过程进行填充,将buf1缓冲区中的处理结果拼接在掩码随机值的末尾。填充过程需要满足国密体系所定义的填充规则,以确保填充后的消息在安全上是可靠的。 4. 使用SM3哈希算法再次对填充过后的消息进行处理,得到256位的摘要值,并将其保存在buf2缓冲区中。 5. 返回计算得到的消息摘要值。 总的来说,sm2_compute_id_digest函数是SM2算法中一个非常重要的组成部分之一,它的计算结果对于算法的安全性和可靠性具有关键的影响。在使用SM2算法进行加密和签名操作时,都需要调用sm2_compute_id_digest函数计算消息摘要,以确保加密和签名结果的正确性和安全性。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值