基于gmssl SM2 签名验签测试程序
前言
在之前的文章中讲解了基于gmssl 的SM2的加解密接口的测试程序,这里主要讲解签名验签的接口测试。
一、sm2 签名流程
代码如下:
void sm2_sig(const EC_GROUP *group, EC_KEY *key,unsigned char * id, int id_len, unsigned char * in_data, int in_len,unsigned char * out_data, int * out_len)
{
const EVP_MD *id_md = EVP_sm3();
const EVP_MD *msg_md = EVP_sm3();
unsigned char dgst[EVP_MAX_MD_SIZE];
size_t dgstlen;
ECDSA_SIG *sm2sig = NULL;
BIGNUM *rr = NULL;
const BIGNUM *sig_r;
const BIGNUM *sig_s;
dgstlen = sizeof(dgst);
if (!SM2_compute_message_digest(id_md, msg_md,
(const unsigned char *)in_data, in_len, id, id_len,
dgst, &dgstlen, key)) {
fprintf(stderr, "error: %s %d\n", __FUNCTION__, __LINE__);
}
/* sign */
sm2sig=SM2_do_sign_ex(dgst, dgstlen, NULL, NULL, key);
ECDSA_SIG_get0(sm2sig, &sig_r, &sig_s);
unsigned char * s_r=NULL;
unsigned char * s_s=NULL;
s_r=BN_bn2hex(sig_r);
s_s=BN_bn2hex(sig_s);
memcpy(out_data,s_r,64);
memcpy(out_data+64,s_s,64);
*out_len=128;
}
二、sm2 验签流程
代码如下:
int sm2_ver(const EC_GROUP *group, EC_KEY *key,unsigned char * id, int id_len, const unsigned char * in_data, int in_len,const unsigned char * sig_data, int sig_len)
{
const EVP_MD *id_md = EVP_sm3();
const EVP_MD *msg_md = EVP_sm3();
unsigned char dgst[EVP_MAX_MD_SIZE];
size_t dgstlen;
unsigned char sig[256];
ECDSA_SIG *sm2sig=NULL;
int i=0;
dgstlen = sizeof(dgst);
if (!SM2_compute_message_digest(id_md, msg_md,
(const unsigned char *)in_data, in_len, id, id_len,
dgst, &dgstlen, key)) {
fprintf(stderr, "error: %s %d\n", __FUNCTION__, __LINE__);
}
sm2sig=ver_sig_set(sig_data,sig_len);
if (1 != SM2_do_verify(dgst, dgstlen, sm2sig, key)) {
return 0;
}
return 1;
}
三、测试结果
结果如下:
priv key:
3C3DDF710D8AE2D875426F8C8E5668D21802E9701B4E0E99E64A00304CAC3CA5
pub x :
A36664C55B5304AA09A38F114FE9D50E762568DA68763E852640AD015B4A1564
pub y:
05E68358CD5A609E1C516BAB516B32DA6EE1D2AB5E39E87DED6AF147F12CA9EF
id data:
ALICE123@YAHOO.COM
mesg data:
0123
==============SM2 sign===========
sign data:
AB0391EC1821E668D71CBEF7872F5903CE0CF4AC99EA2333DF4FE030F9C1F2A8583E7FA0AA4950EE8913B20ED58CCCCAB69494F251F4D6CC702D967C7105ABA4
=========================
verify ok
=========================
通过和网页上的在线sm2工具的交叉检验,结果一致。
总结
注意:
1 签名过程中使用的id 为字符串类型,纯数组不行,因为gmssl源码中计算摘要的过程中会用strlen来判断id的长度。
本文源码
https://download.csdn.net/download/qq_39952971/16062573