Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sm2签名结果长度不一致 #491

Closed
cqchengdan opened this issue May 8, 2018 · 3 comments
Closed

sm2签名结果长度不一致 #491

cqchengdan opened this issue May 8, 2018 · 3 comments

Comments

@cqchengdan
Copy link

sm2几次签名结果长度不一致问题
代码:
`EC_KEY *ec_key = NULL;
ec_key = EC_KEY_new_by_curve_name(NID_sm2p256v1);
EC_KEY_generate_key(ec_key);

unsigned char buf[20] = {0};
memcpy(buf, "encryption standard", 19);

size_t zlen;
unsigned char z[33] = {0};
SM2_compute_message_digest(EVP_sm3(), EVP_sm3(), buf, sizeof(buf),
                           SM2_DEFAULT_ID_GMT09, SM2_DEFAULT_ID_LENGTH, z, &zlen, ec_key);
for(int i=0; i<zlen; i++)
    printf("%02x", z[i]);
printf("\n");
cout << "zlen=" << zlen << endl;

unsigned int signlen;
//SM2_sign(NID_sm3, z, zlen, NULL, &signlen, ec_key);
//cout << "signlen=" << signlen << endl;
//unsigned char *signMsg = new unsigned char[signlen+1];
//memset(signMsg, 0, signlen+1);

unsigned char signMsg[SM2_MAX_SIGNATURE_LENGTH] = {0};
SM2_sign(NID_sm3, z, zlen, signMsg, &signlen, ec_key);
cout << "signlen=" << signlen << endl;
for(int i=0; i<signlen; i++)
    printf("%02x", signMsg[i]);
printf("\n");

EC_KEY_free(ec_key);`

两次执行结果,一次长度71,一次70
[root@localhost Desktop]# ./sig
2e6c09837e3eab76ac9c61bd6a8a3053caf3c3f80dc3fbb4abbe4ce65dcd0cff
zlen=32
signlen=71
304502205c4e47e7c240c2bc71d42ee5d9f59002f36b51b233d2f35884c31edff6bc4a06022100e3d8c43fe32677697938c953040aa7f874cfe0dbad18a50e53f9f3bd18fdd7f8
[root@localhost Desktop]# ./sig
0329b63f13e9fe1f94876d7f7fd399d79750979eee16a07196de8a06d21b37f1
zlen=32
signlen=70
304402204105aaf3b0a9d6dfe817cca6f15f5d408ecb3d1626107a553f8775556d3b649402203bcec2d239c90b03b8536f2d3f037ac3de7cef6bfc8b18fa815f625c70357584

@wumingyuan
Copy link

刚做完这个,你需要的是R||S模式,要在上述基础上做转换:
`
sig = d2i_ECDSA_SIG(NULL, &p, sig_len);
if (sig)
{
ECDSA_SIG_get0(sig, &sig_r, &sig_s);
sig_len = BN_bn2bin(sig_r, sig_bin);
sig_len += BN_bn2bin(sig_s, sig_bin + sig_len);

ECDSA_SIG_free(sig);

}
`
上述p和sig_len分别为sm2_sign返回的签名和长度

@strongbug
Copy link

SM2签名值做了der编码,格式是
SM2Signature :== SEQUENCE{
INTEGER r,
INTEGER s,
}
在大数INTEGER做der编码时,如果首字节的第一个二进制位为1时,前面需要补00字节,所以导致der编码长度为多一个字节,这种情况下SM2签名值得编码长度最大会有两个字节的差距。

@github-actions
Copy link

github-actions bot commented Oct 4, 2020

Marked as stale issue. Will be closed later if no activity for a while.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants