赞
踩
在上一篇文章中《通过openssl生成sm2的公私钥的方法》介绍了如何在openssl系统中生成公私钥对,如何对生成的公私钥对进行验证呢?
在ecparam.c中,添加加解密的代码就可以了,还在《通过openssl生成sm2的公私钥的方法》添加公钥的地方,432行,在生成公钥之后,添加代码如下:
- i = PEM_write_bio_ECPrivateKey(out, eckey, NULL,
- NULL, 0, NULL, NULL);//生成私钥
- //以下为添加代码
- i = PEM_write_bio_EC_PUBKEY(out, eckey);//生成公钥
-
- const char *message = "encryption test data";//测试数据
- const size_t msg_len = strlen(message);
- printf("%s\n",message);
-
- uint8_t *ctext = NULL;
- size_t ctext_len = 0;
- const EVP_MD *digest=EVP_sm3();//摘要方法是sm3
- sm2_ciphertext_size(eckey, digest, msg_len, &ctext_len);
- ctext = OPENSSL_zalloc(ctext_len);
- sm2_encrypt(eckey, digest, (const uint8_t *)message, msg_len,
- ctext, &ctext_len);//加密
- printf("%s\n",ctext);//加密后数据
-
- uint8_t *recovered = NULL;
- size_t recovered_len = msg_len;
- size_t ptext_len = 0;
- sm2_plaintext_size(eckey, digest, ctext_len, &ptext_len);
- recovered = OPENSSL_zalloc(ptext_len);
- sm2_decrypt(eckey, digest, ctext, ctext_len, recovered, &recovered_len);//解密
- printf("%s\n",recovered);//解密后的数据
然后在ecparam.c中添加sm2的头文件
# include "internal/sm2.h"
在apps下面的build.info中添加crypto的依赖
- INCLUDE[openssl]=.. ../include ../crypto/include
- DEPEND[openssl]=libapps.a ../libcrypto.a ../libssl
在openssl目录下,make
然后在apps下面执行
./openssl ecparam -name SM2 -genkey
输出如下:
- -----BEGIN EC PARAMETERS-----
- BgUrgQQAIA==
- -----END EC PARAMETERS-----
- -----BEGIN EC PRIVATE KEY-----
- MGkCAQEEHQDyYYowd8TUhF3XiXX9R0XRsvTkNaVFYcJGR/6CoAcGBSuBBAAgoTwD
- OgAEkq2eq2oLsAnQ4n4Rd00Y6ppaj+8oCc5C0x5k4JktJemrBFJdkDoPLJrQWRFa
- Mc4FiQ+i33LFE44=
- -----END EC PRIVATE KEY-----
- -----BEGIN PUBLIC KEY-----
- ME4wEAYHKoZIzj0CAQYFK4EEACADOgAEkq2eq2oLsAnQ4n4Rd00Y6ppaj+8oCc5C
- 0x5k4JktJemrBFJdkDoPLJrQWRFaMc4FiQ+i33LFE44=
- -----END PUBLIC KEY-----
- encryption test data
- 0uD�mߪ4����~|Fi�o���2�Xں:��
- encryption test data
在加密前和加密后的数据均为,encryption test data,完成验证。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。