c - 函数未生成正确的 openssl rsa key

标签 c linux openssl rsa key-generator

这是我编写的用于生成 openssl rsa 4096 位 key 的 c 函数。

    bool rsa_gen_keys()
    {    
    int             ret = 0;
    RSA             *rsa = NULL;
    BIGNUM          *bignum = NULL;
    BIO             *bio_private = NULL;
    BIO             *bio_public = NULL;
    int              bits = 4096;

    unsigned long k = RSA_F4;

    bignum = BN_new();
    ret = BN_set_word(bignum,k);
    if(ret != 1){
        goto cleanup;
    }

    rsa = RSA_new();
    ret = RSA_generate_key_ex(rsa, bits, bignum, NULL);
    if(ret != 1){
        goto cleanup;
    }
    // write rsa private key to file
    bio_private = BIO_new_file("private_new.pem", "w+");
    ret = PEM_write_bio_RSAPrivateKey(bio_private, rsa, NULL, NULL, 0, NULL, NULL);
    BIO_flush(bio_private);
    // write rsa public key to file
    bio_public = BIO_new_file("public_new.pem", "w+");
    ret = PEM_write_bio_RSAPublicKey(bio_public, rsa);
    if(ret != 1){
        goto cleanup;
    }    
    BIO_flush(bio_public);
cleanup:
    BIO_free_all(bio_private);
    BIO_free_all(bio_public);
    RSA_free(rsa);
    BN_free(bignum);
    return ret;
}

上面函数生成的键好像少了点什么。当我尝试在另一个程序中使用 public_new.pem 文件时,出现以下错误:

140286309791384:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: PUBLIC KEY

但是,如果我使用 openssl 命令生成 key 文件,这些文件可以正常工作。

$openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:4096

我注意到从函数和命令行生成的 key 大小不匹配。这是一条线索,但我需要更改我的函数中的哪些内容才能解决此问题?

-rw-rw-r-- 1 3272 Feb  6 09:19 private_key.pem
-rw-rw-r-- 1  800 Feb  6 09:20 public_key.pem
-rw-rw-r-- 1 3243 Feb  6 10:43 private_new.pem
-rw-rw-r-- 1  775 Feb  6 10:43 public_new.pem

顺便说一句,我用 2048 位 key 尝试了上面的方法,我得到了相同的结果和相同的大小不匹配

最佳答案

openssl genpkey 使用 PEM_write_bio_PrivateKey (PKCS#8) 而不是 PEM_write_bio_RSAPrivateKey (PKCS#1):https://github.com/openssl/openssl/blob/master/apps/genpkey.c#L161-L164 .

您没有显示如何生成 public_key.pem,但它可能是用 PEM_write_bio_PUBKEY (X.509 SubjectPublicKeyInfo) vs PEM_write_bio_RSAPublicKey 编写的>(PKCS#1)。

从 PEM 装甲的角度来看:

  • PKCS#1 公开:开始 RSA 公钥
  • X.509 SubjectPublicKeyInfo:开始公钥
  • PKCS#1 私钥:开始 RSA 私钥
  • PKCS#8:开始私钥

关于c - 函数未生成正确的 openssl rsa key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42072264/

相关文章:

c - C中结构中的多个灵活数组?

c++ - 将原始 PCM 转换为 FLAC?

linux - 在 64 位 ubuntu 上编译 32 位汇编器

linux - Bash - 列出所有子目录中目录名称在文件之前的程序

linux - RHEL6.3如何不使用 'useradd'或 'adduser'命令添加用户?

ssl - ServletRequest.getAttribute ("javax.servlet.request.X509Certificate") 返回 null

检查一个值是否存在于 Cython 的数组中

c++ - 通过对象指针访问成员

ruby - ruby 的 openssl 库中的 sync_close

c++ - 使用 boost 和 openssl 错误的 C++ 中的 JWT(JSON Web token )