RSA_private_encrypt总是失败
我正在学习在我的程序中使用OpenSSL库。 在代码中我生成一个私钥,我立即使用该密钥加密消息。 但总是失败。 请帮助我。
private_key = RSA_generate_key(RSA_KEY_LENGTH, RSA_3, NULL, NULL); if (RSA_check_key(private_key) < 1) { printf("generate_key: key generation failed\n"); exit(-1); } unsigned char msg[25]; unsigned char cipher[128]; strcpy((char*)msg, "hello"); int ret = RSA_private_encrypt(25, msg, cipher, private_key, RSA_PKCS1_OAEP_PADDING); if (ret < 0) { printf("encryption in key generation failed\n"); printf ("%s\n", ERR_error_string (ERR_get_error (), (char *) cipher)); exit (-1); }
这总是失败,这是我用ERR_error_string得到的错误。
error:04066076:lib(4):func(102):reason(118)
错误:04066076:LIB(4):函数(102):原因(118)
您可以使用OpenSSL的errstr
为您提供有意义的错误消息(在大多数情况下):
$ openssl errstr 0x04066076 error:04066076:rsa routines:RSA_EAY_PRIVATE_ENCRYPT:unknown padding type
即使您将其缩小到RSA_PKCS1_OAEP_PADDING
/ RSA_PKCS1_PADDING
,您仍应使用带RSA加密的RSA_PKCS1_OAEP_PADDING
。 所以你的下一个任务是找出你的代码仍然存在的问题。
这里有一篇很好的博客文章,说明为什么你应该避免使用PKCS 1.5填充进行RSA加密: 对于加密令牌行业来说,这是一个糟糕的几年 。
见文档:
男子RSA_private_encrypt
RSA_private_encrypt() signs the flen bytes at from (usually a message digest with an algorithm identifier) using the private key rsa and stores the signature in to. to must point to RSA_size(rsa) bytes of memory. padding denotes one of the following modes: RSA_PKCS1_PADDING PKCS #1 v1.5 padding. This function does not handle the algorithmIdentifier specified in PKCS #1. When generating or verifying PKCS #1 signatures, RSA_sign(3) and RSA_verify(3) should be used. RSA_NO_PADDING Raw RSA signature. This mode should only be used to implement cryptographically sound padding modes in the application code. Signing user data directly with RSA is insecure.
我不知道你从哪里得到RSA_PKCS1_OAEP_PADDING,但是上面列出了唯一支持的填充。
我找到了这个问题的原因。 实际上填充方法RSA_PKCS1_OAEP_PADDING在我的centos和ubuntu机器上都不适合我。 一旦我将其更改为RSA_PKCS1_PADDING,它就开始正常工作了。 但我不确定为什么会这样。