如何使用OpenSSL库创建证书请求

时间:2017-06-07 11:17:50

标签: ios ssl openssl csr

我正在尝试使用openSSL在iOS中以编程方式创建证书请求。我最终获得了testKey.pem(私钥)和test.csr,并且第一个在linux中运行良好(通过openssl命令),但test.csr接缝很奇怪,无法正确识别和使用。这是我在OC中的代码。

- (void)genCertReq {
    if (!X509_REQ_set_version(csr.req, csr.ver)) {
        LOG(@"set_version failed");
        goto error;
    }
    [self fillDN]; 
    /* subject name */
    if (!X509_REQ_set_subject_name(csr.req, csr.subject)) {
        LOG(@"subject_name failed");
        goto error;
    }
    rsaPair = RSA_generate_key(bits, e, NULL, NULL);
    const char *keyPathChar = [SPFileManager openFile:testKey];
    BIO *bp = NULL;
    bp = BIO_new_file(keyPathChar, "w");
    PEM_write_bio_RSAPrivateKey(bp, rsaPair, NULL, NULL, 0, NULL, NULL);
    BIO_free(bp);
    /* pub key */
    if (1 != EVP_PKEY_assign_RSA(evpKey, rsaPair)) {
        LOG(@"assign_RSA failed");
        goto error;
    }
    if (!X509_REQ_set_pubkey(csr.req, evpKey)) {
        LOG(@"set_pubkey failed");
        goto error;
    }
    /* attribute */
    csr.md = EVP_sha1();
    if (!X509_REQ_digest(csr.req, csr.md, (unsigned char *)csr.mdout, (unsigned int *)&csr.mdlen)) {
        LOG(@"req_digest failed");
        goto error;
    }
    if (!X509_REQ_sign(csr.req, evpKey, csr.md)) {
        LOG(@"req_sign failed");
        goto error;
    }
    const char *csrPathChar = [SPFileManager openFile:csrName];
    bp = BIO_new_file(csrPathChar, "w");
    PEM_write_bio_X509_REQ(bp, csr.req);
    BIO_free(bp);

    OpenSSL_add_all_algorithms();
    if (X509_REQ_verify(csr.req, evpKey) < 0) {
        LOG(@"req_verify failed");
        goto error;
    }
    X509_REQ_free(csr.req);
    return;
error:
    X509_REQ_free(csr.req);
    return;
}

testKey.pem采用PKCS1格式,看起来像--BEGIN RSA PRIVATE KEY---test.csr看起来像---BEGIN CERTIFICATE REQUEST---,但我认为不对。

任何帮助将不胜感激,谢谢。

0 个答案:

没有答案