1

我正在研究在嵌入式系统中使用 RSA 加密。为此,我将使用 polarssl 代码。

我已经在 128 位上进行了加密,但我在签名部分遇到了问题。当我运行代码时,验证时出现填充错误(POLARSSL_ERR_RSA_INVALID_PADDING -0x4100)

下面是代码。问题代码接近尾声,最上面一行是关于加密的。仍然有助于背景信息。

int main()
{
    size_t len;
    rsa_context rsa;
    unsigned char rsa_plaintext[PT_LEN];
    unsigned char rsa_decrypted[PT_LEN];
    unsigned char rsa_ciphertext[KEY_LEN];
    unsigned char rsa_hash[PT_LEN];
    unsigned char rsa_sig_out[PT_LEN];
    unsigned char rsa_hash_result[PT_LEN];

rsa_init( &rsa, RSA_PKCS_V15, 0 );
rsa.len = KEY_LEN;

mpi_read_string( &rsa.N , 16, RSA_N  );
mpi_read_string( &rsa.E , 16, RSA_E  );
mpi_read_string( &rsa.D , 16, RSA_D  );
mpi_read_string( &rsa.P , 16, RSA_P  );
mpi_read_string( &rsa.Q , 16, RSA_Q  );
mpi_read_string( &rsa.DP, 16, RSA_DP );
mpi_read_string( &rsa.DQ, 16, RSA_DQ );
mpi_read_string( &rsa.QP, 16, RSA_QP );

// Checking the public and private keys
if( rsa_check_pubkey(  &rsa ) != 0 ||
    rsa_check_privkey( &rsa ) != 0 ) {
    printf( "Public/Private key error! \n" );
    exit(0);
}

memcpy( rsa_plaintext, RSA_PT, PT_LEN );

if( rsa_pkcs1_encrypt( &rsa, &myrand, NULL, RSA_PUBLIC, PT_LEN,
                       rsa_plaintext, rsa_ciphertext ) != 0 ) {
    printf( "Encryption failed! \n" );
    exit(0);
}
if( rsa_pkcs1_decrypt( &rsa, &myrand, NULL, RSA_PRIVATE, &len,
                       rsa_ciphertext, rsa_decrypted,
                       sizeof(rsa_decrypted) ) != 0 ) {
    printf( "Decryption failed! \n" );
    exit(0);
}
if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 ) {
    printf( "Compare failed! \n" );
    exit(0);
}
printf("Oh when it all falls down!\n");

// Signing and Verifying message
sha2(rsa_plaintext, len, rsa_hash, 0); //hashing the message 
if (rsa_pkcs1_sign( &rsa, &myrand, NULL, RSA_PRIVATE, SIG_RSA_SHA256, 0, rsa_hash, rsa_sig_out ) != 0) {
    printf( "Signing failed! \n" );
    exit(0);
}
/*
if (rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC, SIG_RSA_SHA256, 0, rsa_sig_out, rsa_hash_result ) != 0) {
    printf( "Verifying signature failed! \n" );
    exit(0);
}
*/
printf("Error Message!:%d \n", rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC,
SIG_RSA_SHA256, 0, rsa_sig_out, rsa_hash_result ));
exit(0);

if( memcmp( rsa_hash, rsa_hash_result, len ) != 0 )
{
    printf( "Signature not verified! \n" );
    exit(0);
}
rsa_free(&rsa);

return 0;

}

任何人都知道我如何解决这个问题并继续前进。请告诉我。谢谢我在 Windows 的 MinGw gcc 编译器上运行它。rsa 代码依赖于 bignum、md 和 sha2。

4

1 回答 1

3

哈希失败的原因是你rsa_hash在签名rsa_hash_result之前或者验证之前没有填写。

rsa_pkcs1_sign()rsa_pkcs1_verify()签名并验证所提供的哈希值。他们不做散列,因为他们不知道数据。(即rsa_plaintext永远rsa_ciphertext不要输入签名或验证功能)。

因此,在您致电之前,rsa_pkcs1_sign()您应该运行sha256(rsa_plaintext, rsa_hash);sha256(rsa_ciphertext, rsa_hash);(取决于您的“协议”的工作方式)。

然后在验证之前,您运行sha256(XXX, rsa_hash_result);并提供该值,rsa_pkcs1_verify()以便它可以实际验证您的哈希。

于 2013-11-05T15:24:38.423 回答