Your code contains several mistakes. The direct cause of the segfault is the fact that the variable pkey
is never assigned any value after initializing it with 0
. EVP_PKEY_get1_RSA(pkey)
segfaults as a consequence. You probably intended to do
EVP_PKEY *pkey = PEM_read_bio_PUBKEY(bo, NULL, NULL, NULL);
However, with the PEM that you posted, that will not work. The header of the PEM indicates that this is an RSA key stored in "traditional" format. PEM_read_bio_RSAPublicKey
is capable of reading such keys:
RSA *rsa = PEM_read_bio_RSAPublicKey(bo, NULL, NULL, NULL);
Then your choice of RSA_NO_PADDING
when invoking RSA_public_encrypt
is not right. In order to use that, the plaintext must be the exact same length as the key size. You could try using RSA_PKCS1_PADDING
instead.
Finally, like mentioned in the comment section as well, using strlen
on cipher text is incorrect, because it is not a 0-terminated string.
In general, you should check all return values for all OpenSSL functions invoked, to see when/if something went wrong.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…