加载公钥以创建用于公共加密的rsa对象

时间:2017-07-16 00:42:16

标签: c openssl rsa public-key pem

我正在尝试从生成的公钥加载rsa对象。我使用PEM_write_bio_RSAPublicKey生成公钥字符串。然后我使用PEM_read_bio_RSA_PUBKEY从公钥字符串加载rsa对象。问题是rsa对象为null。据我所知,生成的字符串看起来还不错。有什么想法吗?

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAxIReUspesPy6a4CPBjt/4Jt+H13q9MekMiutzNKdNO1uuwqcdqDX
pKPeTKXyUH6oCyRdUxkk6IVXGlBlxtW7OsxaYWhpfl9z3CCERCEpFmzN++dvlK2v
mckFL66e9q6Y+HwgyP1LJqrszeqlg2d29TCVKfD/UURVNmc/nPPjs9nO+IDhh7+P
NTQ2OqGBq8ghwVL5ZZyW3yVO5OAbRB6pjKBe9+j4B2TGnD5JO9Nu0jlFANZOKFJu
HDVE3XuTvOkuzL2i8Lwp4Myk42tbIgcCe4G58vKFddL651rWhg4hN3fRSx5YtDnQ
r5cgfNBOAww58S8lwXgU8lvzvEoNV+WMgwIDAQAB
-----END RSA PUBLIC KEY-----

gcc test_public_private_key.c -lcrypto -o test

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>

char* get_public_key() {

        RSA* rsa = RSA_new();
        int kbits = 2048;
        BIGNUM* bne = BN_new();
        BN_set_word(bne, RSA_F4);

        int status = RSA_generate_key_ex(rsa, kbits, bne, NULL);
        if(status == 0) {
                fprintf(stderr, "rsa key generation failed\n");
        }


        BIO *bio = BIO_new(BIO_s_mem());
        PEM_write_bio_RSAPublicKey(bio, rsa);

        int length = BIO_pending(bio);

        char* pem_key = malloc(length+1);
        memset(pem_key, '\0', length+1);

        BIO_read(bio, pem_key, length);

        return pem_key;

}

int main(int argc, char* argv[]) {

        char* public_key = get_public_key();

        printf("%s", public_key);

        BIO* keybio = BIO_new_mem_buf(public_key, -1);

        if (keybio == NULL) {
                fprintf(stderr, "failed to create key BIO");
        }

        printf("keybio: %p\n", keybio);
        RSA* rsa = PEM_read_bio_RSA_PUBKEY(keybio, NULL, NULL, NULL);
        printf("rsa result %p\n", rsa);
        BIO_free(keybio);

        free(public_key);

        return 0;
}

1 个答案:

答案 0 :(得分:3)

我认为最好补充说这不起作用的原因是因为PEM_read_RSA_PUBKEY期望SubjectPublicKeyInfo结构以BEGIN PUBLIC KEY开头,而PEM_read_RSAPublicKey期望RSAPublicKey结构,以BEGIN RSA PUBLIC KEY开头 PEM_write_bio_RSAPublicKey生成后者,后者对应于第二个函数PEM_read_RSAPublicKey