【问题标题】:openssl pkcs12 command programmatically Objective-C / Copenssl pkcs12 命令以编程方式 Objective-C / C
【发布时间】:2014-12-09 10:16:05
【问题描述】:

我正在尝试从 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;

我现在如何获取私钥?

【问题讨论】:

    标签: c openssl key extract private


    【解决方案1】:

    您的密钥在您的 EVP_PKEY *pkey 对象中。该对象是一个抽象密钥(EVP = 信封),但您可以根据您拥有的密钥类型来提取真正的密钥:

     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 密钥,那么您拥有一个私钥/公钥对的所有组件,这些组件是非常大的数字,存储在 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

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多