【问题标题】:RSA_private_decrypt errorRSA_private_decrypt 错误
【发布时间】:2017-09-19 07:07:58
【问题描述】:

对不起,愚蠢的问题,我看过很多例子,但找不到答案。 尝试使用 rsa 加密和解密文件:

加密

 ptext = (unsigned char *)malloc(key_size);
    ctext = (unsigned char *)malloc(key_size);
    while (1) {
            inlen = _read(in, ptext, key_size);
            if (inlen <= 0) break;
            outlen = RSA_public_encrypt(inlen, ptext, ctext, pubKey, 
    RSA_PKCS1_PADDING);
            if (outlen != RSA_size(pubKey)) exit(-1);
            _write(out, ctext, outlen);
        }

解密:

while (1) {     
        inlen = _read(in, ctext, key_size);
        printf("Read %i bytes\n", inlen);
        if (inlen <= 0) break;
        outlen = RSA_private_decrypt(key_size-11, ctext, ptext, privKey, RSA_PKCS1_PADDING);
        printf("RSA returns %i\n", outlen);
        if (outlen < 0)
        {
            fprintf(stderr, "OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
            exit(0);
        }
        _write(out, ptext, outlen);
}

程序输出:

Read 431 bytes
RSA returns -1
OpenSSL error: error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error

key_size 或 key_size-11 -> 没有变化。 请帮忙绕过这个错误。

【问题讨论】:

  • 您正在写入RSA_size(pubKey) 字节的数据,然后读回key_size 字节。它是否正确? key_size 是否等于 RSA_size(pubKey)?是什么让你决定尝试从 key_size 中减去 11?
  • 我将读取值更改为 rsa_size(pubKey),但得到了同样的错误。
  • RSA_size(pubKey) = 512 and key_size=512

标签: c++ c cryptography rsa


【解决方案1】:

对于 RSA 解密,flen 必须是 RSA_size(pubkey),而不是 RSA_size(pubkey) - 11。因此像

outlen = RSA_private_decrypt(RSA_size(pubKey), ctext, ptext, privKey, RSA_PKCS1_PADDING);

应该可以。解密后的明文应该包含在ctext[0] ... ctext[outlen-1]中。

【讨论】:

  • 还是同样的错误:读取 512 字节 RSA 返回 -1 OpenSSL 错误:error:0407109F:rsaroutines:RSA_padding_check_PKCS1_type_2:pkcs 解码错误
【解决方案2】:

这就是我在我的项目中使用 RSA crypt 函数的方式。尝试与您的实现进行比较

int rsa_oaep_encrypt(EVP_PKEY *publicKey, const unsigned char *plaintext, const size_t plaintextLen, unsigned char *ciphertext, size_t *ciphertextLen)
{
 int sts = -1;
 if ( (*ciphertextLen = RSA_public_encrypt(plaintextLen, plaintext, ciphertext, publicKey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) > 0)
    sts = 0;
 return sts;
}

int rsa_oaep_decrypt(EVP_PKEY *privateKey, const unsigned char *ciphertext, const size_t ciphertextLen, unsigned char *plaintext, size_t *plaintextLen)
{
 int sts = -1;
 if ( (*plaintextLen = RSA_private_decrypt(ciphertextLen, ciphertext, plaintext, privateKey->pkey.rsa, RSA_PKCS1_OAEP_PADDING)) > 0)
    sts = 0;
 return sts;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2012-03-06
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多