2015-02-24 16 views
5

Um Zertifikat in OpenSSL zu signieren verwende ich X509_sign() Funktion, indem Sie es mit einer Anfrage (wie X509_REQ*), einem Signierungsschlüssel und einem Digest.Zertifikat in PKCS # 11 signieren

Jetzt habe ich meinen Signaturschlüssel in HSM gespeichert, also kann ich ihn nicht extrahieren, um das Zertifikat zu signieren. Leider bietet PKCS # 11 kein Äquivalent zu X509_sign(). Alles, was es hat, ist C_Sign()/C_SignUpdate()/C_SignFinal() Familie von Funktionen, die auf Rohdaten arbeiten, nicht auf Zertifikaten.

Kann mir jemand mit C/C++ - Beispielcode helfen, PKCS # 11 zum Signieren eines mit OpenSSL erstellten Zertifikats zu verwenden?

Antwort

4

Der folgende Code kennzeichnet die angegebene X509 * Struktur in HSM. Die Fehlerbehandlung ist der Übersichtlichkeit halber weggelassen.

void signCertInHsm(X509* x509, unsigned long pkcs11SigningAlgo, CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE p11session, CK_OBJECT_HANDLE pkcs11PrivKeyHandle) 
{ 
    x509->cert_info->enc.modified = 1; 

    // set signature algorithm in the certificate 
    if (x509->cert_info->signature) 
    { 
     const int signingAlgoNid = pkcs11SignatureAlgorithmToNid(pkcs11SigningAlgo); 
     X509_ALGOR_set0(x509->cert_info->signature, OBJ_nid2obj(signingAlgoNid), V_ASN1_NULL, NULL); 
    } 
    if (x509->sig_alg) 
    { 
     const int signingAlgoNid = pkcs11SignatureAlgorithmToNid(pkcs11SigningAlgo); 
     X509_ALGOR_set0(x509->sig_alg, OBJ_nid2obj(signingAlgoNid), V_ASN1_NULL, NULL); 
    } 

    // DER-encode certificate 
    unsigned char *certDerBuf = NULL; 
    const size_t certDerLen = ASN1_item_i2d((ASN1_VALUE*)x509->cert_info, &certDerBuf, ASN1_ITEM_rptr(X509_CINF)); 

    CK_MECHANISM mechanism = { pkcs11SigningAlgo, NULL_PTR, 0 }; 
    p11->C_SignInit(p11session, &mechanism, pkcs11PrivKeyHandle); 

    // determine signature size 
    CK_ULONG signatureSize = 0; 
    p11->C_Sign(p11session, certDerBuf, certDerLen, NULL, &signatureSize); 

    // sign 
    if (x509->signature->data) 
     OPENSSL_free(x509->signature->data); 
    x509->signature->data = (unsigned char*)OPENSSL_malloc(signatureSize); 
    x509->signature->length = signatureSize; 
    p11->C_Sign(p11session, certDerBuf, certDerLen, x509->signature->data, &signatureSize); 

    x509->signature->flags&= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07); 
    x509->signature->flags|=ASN1_STRING_FLAG_BITS_LEFT; 

    OPENSSL_free(certDerBuf); 
} 

int pkcs11SignatureAlgorithmToNid(unsigned long algo) 
{ 
    switch(algo) 
    { 
    case CKM_SHA1_RSA_PKCS: return NID_sha1WithRSAEncryption; 
    case CKM_SHA256_RSA_PKCS: return NID_sha256WithRSAEncryption; 
    //... add more mappings that your app supports 
    default: throw std::invalid_argument("Not supported signature algorithm"); 
    } 
} 
+0

Große Antwort, Andrei! Genau auf den Punkt und macht, was es soll. –