使用openssl.exe使用256位RSA密钥对20字节消息进行签名,但未在代码中进行签名 [英] Signing 20-byte message with 256-bit RSA key working with openssl.exe but not in code

查看:447
本文介绍了使用openssl.exe使用256位RSA密钥对20字节消息进行签名,但未在代码中进行签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个256位私钥,我想用它来签名SHA-1摘要(20个字节).直接使用openssl似乎可行

I have a 256-bit private key that I want to use to sign a SHA-1 digest (20 bytes). Using openssl directly it seems to work

回声不重要| openssl dgst -sha1 -binary | openssl rsautl -sign -inkey 256bit_private_key.pem | openssl enc -base64

echo doesntmatter | openssl dgst -sha1 -binary | openssl rsautl -sign -inkey 256bit_private_key.pem | openssl enc -base64

为我提供了预期的Base64输出.

gives me a Base64 output as expected.

但是使用OpenSSL失败,并显示错误:04075070:rsa例程:RSA_sign:摘要对于rsa密钥而言太大".如下所示,我将20字节(SHA_DIGEST_LENGTH = 20)SHA-1摘要作为输入传递给RSA_sign.即使使用填充,它也不应超过我可以使用256位模数密钥加密的最大32个字节吗?!

But doing it with the OpenSSL fails with "error:04075070:rsa routines:RSA_sign:digest too big for rsa key". As you can see below, I'm passing the 20-byte (SHA_DIGEST_LENGTH=20) SHA-1 digest as input to RSA_sign. Even with padding it shouldn't be more than the maximum of 32 bytes that I can encrypt with a 256 bit modulus key?!

unsigned char digest[SHA_DIGEST_LENGTH];
SHA1(message, messageSize, digest);

unsigned int privateKeySize = RSA_size(privateKey); // 256 bits = 32 bytes
unsigned char* signature = new unsigned char[privateKeySize];
unsigned int signatureSize;

int res = RSA_sign(NID_sha1, digest, SHA_DIGEST_LENGTH, signature, &signatureSize, privateKey);

if(res == 0)
{
    int err = ERR_get_error(); // 67588208
    char *s = ERR_error_string(err, 0); // error:04075070:lib(4):func(117):reason(112)

    delete [] signature;

    [...]
}

我在代码中做错什么了?

What am I doing wrong in the code?

推荐答案

猜猜我找到了解决方案. openssl rsautl -sign使用RSA_private_encrypt而不是RSA_sign(这是我期望的). RSA_sign创建的结构比我提供的20字节消息更长,因此由于给定的错误而失败.

Guess I found the solution. openssl rsautl -sign uses RSA_private_encrypt instead of RSA_sign (what I would have expected). RSA_sign creates a longer structure than the 20-bytes message I provided, so it fails with the given error.

这篇关于使用openssl.exe使用256位RSA密钥对20字节消息进行签名,但未在代码中进行签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆