简体   繁体   English

RSA_verify中预期的数据类型是什么,无法验证从Java生成的签名

[英]what is the type of data expected in RSA_verify, can't verify a signature generated from Java

I create a signature on Java using : 我使用以下命令在Java上创建签名:

String message = "my message";
byte[] data = message.getBytes();
byte[] result;
Signature sig = Signature.getInstance("SHA512withRSA");
sig.initSign(this.privateKey);
sig.update(data);
result = sig.sign();

Then I save result as a Hex String into a text file, and using openssl I try to verify: 然后,将结果作为十六进制字符串保存到文本文件中,并使用openssl尝试验证:

string signature//read hex string in the text file 
string message = "my message";
RSA *rsaPkey = NULL;

FILE *pemFile;
fopen_s(&pemFile, publicKeyFile, "r");
rsaPkey = PEM_read_RSA_PUBKEY(pemFile, &rsaPkey, NULL, NULL);
fclose(pemFile);

if(rsaPkey == NULL)
{
    RSA_free(rsaPkey);
    return 0;
}

int type                = NID_sha512;
const char *m           = message.c_str();
unsigned int m_len      = message.length();
int size                = RSA_size(rsaPkey);
unsigned char *sigret   = (unsigned char*) signature.c_str();
unsigned int siglen     = signature.length();

unsigned char digest[SHA512_DIGEST_LENGTH];

SHA512_CTX ctx;
SHA512_Init(&ctx);
SHA512_Update(&ctx, m, m_len);
SHA512_Final(digest, &ctx);

int r = RSA_verify(type, digest, SHA512_DIGEST_LENGTH, sigret, siglen, rsaPkey);

r is always 0, which means the verification has failed. r始终为0,表示验证失败。 I think it's because it's expecting the message or the signature in a specific format than the hex I got from Java but i don't know what exaclty. 我认为这是因为它期望消息或签名采用特定格式,而不是我从Java获得的十六进制格式,但我不知道该怎么做。

UPDATE UPDATE

After using the digest as suggested by Pras, I get this message error when I use ERR_get_error : error:04091068:rsa routines:INT_RSA_VERIFY:bad signature 在按照Pras的建议使用摘要之后,当我使用ERR_get_error时出现以下error:04091068:rsa routines:INT_RSA_VERIFY:bad signature消息: error:04091068:rsa routines:INT_RSA_VERIFY:bad signature

From RSA_verify() man page: 从RSA_verify()手册页:

RSA_verify() verifies that the signature sigbuf of size siglen matches a given message digest m of size m_len. RSA_verify()验证大小为siglen的签名sigbuf是否与大小为m_len的给定消息摘要m相匹配。 type denotes the message digest algorithm that was used to generate the signature. type表示用于生成签名的消息摘要算法。 rsa is the signer's public key. rsa是签名者的公钥。

So the second and third arguments are supposed to be message digest and digest length not actual message and message length that was signed 因此,第二个和第三个参数应该是消息摘要和摘要长度,而不是实际的消息和已签名的消息长度

It could be that byte[] data = message.getBytes(); 可能是byte[] data = message.getBytes(); may not give the same sequence of bytes as message.c_str() . 可能不会给出与message.c_str()相同的字节序列。 I suggest you check it with a debugger. 我建议您使用调试器进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM