c - openssl pkcs12 命令以编程方式 Objective-C/C

标签 c openssl key extract private

我正在尝试从 C 中的 p12 文件中获取私钥。 在控制台中我只需输入

openssl pkcs12 -in some.p12 -out kestore.pem -nodes

在 pem 中我有私钥。

我设法像这样加载 p12 文件

    NSString *path = [[NSBundle bundleForClass:self.class] pathForResource:@"some" ofType:@"p12"];
    const char *pathCString = [path cStringUsingEncoding:NSUTF8StringEncoding];
    FILE *p12File = fopen(pathCString, "rb");
    if (p12File == nil) {
        return nil;
    }
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    PKCS12 *p12 = NULL;
    p12 = d2i_PKCS12_fp(p12File, NULL);

    if (p12 != NULL) {
        const char *pw = "supersecretpass";
        //int PKCS12_parse(PKCS12 * p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) * *ca);
        EVP_PKEY *pkey;
        X509 *cert;
        STACK_OF(X509) * ca;
        int result = PKCS12_parse(p12, pw, &pkey, &cert, &ca);
        NSLog(@"result %d", result);
        PKCS12_free(p12);
    }

    fclose(p12File);
    return nil;

现在如何获取私钥?

最佳答案

您的 key 位于您的 EVP_PKEY *pkey 对象中。该对象是一个抽象 key (EVP = envelop),但您可以根据您拥有的 key 类型来提取真正的 key :

 RSA *EVP_PKEY_get1_RSA(EVP_PKEY *pkey);
 DSA *EVP_PKEY_get1_DSA(EVP_PKEY *pkey);
 DH *EVP_PKEY_get1_DH(EVP_PKEY *pkey);
 EC_KEY *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey);

这里有关于它的文档:https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_get1_RSA.html

例如,如果您有 RSA key ,则您拥有私钥/公钥对的所有组成部分,这些组成部分是存储在 BIGNUM 对象中的非常大的数字:

 const BIGNUM *RSA_get0_n(const RSA *d);
 const BIGNUM *RSA_get0_e(const RSA *d);
 const BIGNUM *RSA_get0_d(const RSA *d);
 const BIGNUM *RSA_get0_p(const RSA *d);
 const BIGNUM *RSA_get0_q(const RSA *d);
 const BIGNUM *RSA_get0_dmp1(const RSA *r);
 const BIGNUM *RSA_get0_dmq1(const RSA *r);
 const BIGNUM *RSA_get0_iqmp(const RSA *r);
 void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d);
 void RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q);

这里有关于它的文档:

https://www.openssl.org/docs/manmaster/man3/RSA_get0_e.html

https://www.openssl.org/docs/man1.1.0/man3/RSA_get0_key.html

关于c - openssl pkcs12 命令以编程方式 Objective-C/C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26363874/

相关文章:

MySQL 键/唯一键

javascript - 为什么集合的键等于值?

c - C 中的匿名管道与 execlp

c - 限制信号处理程序仅捕获来自定义它的特定文件的信号

c - 如何在C程序中将矩阵的第一列元素复制到第二列

c - MD5 函数如何工作?

.net - 提取C#中的私钥字节

c - 如何用C语言创建操作系统?

php - Android应用内购买服务器签名验证使用php OpenSSL

regex - 查询键中的 MongoDB 正则表达式模式或通配符