我在使用生成的RSA pubkey加密字符串时遇到问题。此密钥存储在unsigned char数组中。以下是该密钥的示例
char *testkey = "-----BEGIN RSA PUBLIC KEY-----\n"
"MIIBCgKCAQEA3InRLxdx25R6eA4PyXcYzKyFiJULS3ypqlETztAW488XkEM263vJ\n"
"SY5xpfwph9thcsjYUI3H60qxaTRVhNxbzbsG0ELkEudm4cLMn2oVpphT4cB3zx6V\n"
"az1cuzIfmL34M8YiRQw6MvdaDJS34y15dXDm0BSXF7sanZaYrHvu84j5mQVK0OWq\n"
"kvpVs+J55xul/IQsSEWr94HjPupdDYzGXsEiQ7p5cNrvKgjGKqKV177EYROVVgVp\n"
"gAWm0G6aDrfDLKqsXo8RXj4dyyuZqoL2e7Fa46Gz4I+tb2SWkEwLGpqBe/CUDzDh\n"
"9aLhaTijDQhcaR5+u88XNbarckKU96wiiQIDAQAB\n"
"-----END RSA PUBLIC KEY-----\0";
我目前已编写此代码进行加密
RSA *rsa = NULL;
BIO *key_bio;
static const int bit = 2048;
key_bio = BIO_new_mem_buf(testkey, -1);
if(key_bio == NULL){
printf("No key bio \n");
exit(1);
}
rsa = PEM_read_bio_PUBKEY(key_bio, NULL, NULL, NULL);
if(rsa == NULL){
fprintf(stderr, "Error loading RSA Public Key File.\n");
ERR_print_errors_fp(stderr);
exit(1);
}
// Alloc the encrypted buffer
e->enckey = calloc(1, 2048);
int res = RSA_public_encrypt(strlen((char*)e->key->key), e->key->key, e->enckey, rsa, RSA_PKCS1_PADDING);
if(res == -1){
printf("Failed to encrypt AES key \n");
printf("Error: strerror(errno)\n");
}
然而,这不起作用。我认为它与密钥的格式有关,但是我还没有设法找到如何转换它,并使用RSA结构来进行加密。
有什么想法吗?
答案 0 :(得分:0)
现在似乎工作正常,使用此insead:
PEM_read_bio_RSAPublicKey(key_bio, &rsa, 0, NULL);
这可能与KEY的格式有关。