testcrmf.c

来自「支持SSL v2/v3, TLS, PKCS #5, PKCS #7, PKCS」· C语言 代码 · 共 1,528 行 · 第 1/3 页

C
1,528
字号
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ *  * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. *  * The Original Code is the Netscape security libraries. *  * The Initial Developer of the Original Code is Netscape * Communications Corporation.  Portions created by Netscape are  * Copyright (C) 1994-2000 Netscape Communications Corporation.  All * Rights Reserved. *  * Contributor(s): *  * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL"), in which case the provisions of the GPL are applicable  * instead of those above.  If you wish to allow use of your  * version of this file only under the terms of the GPL and not to * allow others to use your version of this file under the MPL, * indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by * the GPL.  If you do not delete the provisions above, a recipient * may use your version of this file under either the MPL or the * GPL. */#include "crmf.h"#include "secrng.h"#include "secpkcs5.h"#include "pk11func.h"#include "pkcs11.h"#include "secmod.h"#include "secmodi.h"#include "key.h"#include "prio.h"#include "pqggen.h"#include "cmmf.h"#include "seccomon.h"#include "secmod.h"#include "prlock.h"#include "secmodi.h"#include "pkcs11.h"#include "pk11func.h"#include "secitem.h"#include "key.h"#include "rsa.h"#include "secpkcs5.h"#include "secasn1.h"#include "sechash.h"#include "cert.h"#include "secerr.h"#include <stdio.h>#include "prprf.h"#if !defined(XP_UNIX) && !defined(LINUX)extern int getopt(int, char **, char*);extern char *optarg;#endif#define MAX_KEY_LEN 512int64 notBefore;char *personalCert      = NULL;char *recoveryEncrypter = NULL;char *caCertName        = NULL;CERTCertDBHandle *db;SECKEYKeyDBHandle *keydb;void debug_test(SECItem *src, char *filePath){    PRFileDesc *fileDesc;    fileDesc = PR_Open (filePath, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 			0666);    if (fileDesc == NULL) {        printf ("Could not cretae file %s.\n", filePath);	return;    }    PR_Write(fileDesc, src->data, src->len);    }SECStatusget_serial_number(long *dest){   RNGContext *rng;   SECStatus   rv;   if (dest == NULL) {       return SECFailure;   }   rng = RNG_CreateContext();   if (rng == NULL) {       *dest = 0;       return SECFailure;   }   rv = RNG_GenerateRandomBytes(rng, (void*)dest, sizeof(long));   RNG_DestroyContext(rng, PR_TRUE);    return SECSuccess;}char *promptForPassword (PK11SlotInfo *slot, PRBool retry, void *cx){    char passWord[80];    char *retPass = NULL;        if (retry) {        printf ("Incorrect password.  Please re-enter the password.\n");    }     printf ("WARNING: Password will be echoed to the screen.\n");    printf ("Please enter the password for slot \"%s\":", 	    PK11_GetTokenName(slot));    scanf ("%s", passWord);    retPass = PORT_Strdup(passWord);    return retPass;}PK11RSAGenParams *GetRSAParams(void) {    PK11RSAGenParams *rsaParams;    rsaParams = PORT_ZNew(PK11RSAGenParams);    if (rsaParams == NULL)      return NULL;    rsaParams->keySizeInBits = MAX_KEY_LEN;    rsaParams->pe = 0x1001;        return rsaParams;    }SECStatusSetSlotPassword(PK11SlotInfo *slot){    char userPin[80];    printf ("Initialization of PIN's for your Database.\n");    printf ("------------------------------------------\n");    printf ("Please enter the PIN's for your Database.\n");    printf ("Warning: ALL PIN'S WILL BE ECHOED TO SCREEN!!!\n");    printf ("Now enter the PIN for the user: ");    scanf  ("%s", userPin);    return PK11_InitPin (slot, NULL, userPin);}PQGParams*GetDSAParams(void){    PQGParams *params = NULL;    PQGVerify *vfy = NULL;    SECStatus  rv;    rv = PQG_ParamGen(0, &params, &vfy);    if (rv != SECSuccess) {        return NULL;    }    PQG_DestroyVerify(vfy);    return params;}CERTSubjectPublicKeyInfo *GetSubjectPubKeyInfo(SECKEYPrivateKey **destPrivKey, 		     SECKEYPublicKey  **destPubKey) {    CERTSubjectPublicKeyInfo *spki       = NULL;    SECKEYPrivateKey         *privKey    = NULL;    SECKEYPublicKey          *pubKey     = NULL;    PK11SlotInfo             *keySlot    = NULL;    PK11RSAGenParams         *rsaParams  = NULL;    PQGParams                *dsaParams  = NULL;        keySlot = PK11_GetInternalKeySlot();    PK11_Authenticate(keySlot, PR_FALSE, NULL);    PK11_Authenticate(PK11_GetInternalSlot(), PR_FALSE, NULL);    rsaParams  = GetRSAParams();    privKey = PK11_GenerateKeyPair(keySlot, CKM_RSA_PKCS_KEY_PAIR_GEN,				   (void*)rsaParams, &pubKey, PR_FALSE,				   PR_FALSE, NULL);/*    dsaParams = GetDSAParams();    if (dsaParams == NULL) {        return NULL;    }    privKey = PK11_GenerateKeyPair(keySlot, CKM_DSA_KEY_PAIR_GEN,				   (void*)dsaParams, &pubKey, PR_FALSE,				   PR_FALSE, NULL);*/    if (privKey == NULL || pubKey == NULL) {        if (pubKey) {	    SECKEY_DestroyPublicKey(pubKey);	}	if (privKey) {	    SECKEY_DestroyPrivateKey(privKey);	}	return NULL;    }    spki = SECKEY_CreateSubjectPublicKeyInfo(pubKey);    *destPrivKey = privKey;    *destPubKey  = pubKey;    return spki;}SECStatusInitPKCS11(void){    PK11SlotInfo *cryptoSlot, *keySlot;    PK11_SetPasswordFunc(promptForPassword);    cryptoSlot = PK11_GetInternalSlot();    keySlot    = PK11_GetInternalKeySlot();        if (PK11_NeedUserInit(cryptoSlot) && PK11_NeedLogin(cryptoSlot)) {        if (SetSlotPassword (cryptoSlot) != SECSuccess) {	    printf ("Initializing the PIN's failed.\n");	    return SECFailure;	}    }        if (PK11_NeedUserInit(keySlot) && PK11_NeedLogin(keySlot)) {        if (SetSlotPassword (keySlot) != SECSuccess) {	    printf ("Initializing the PIN's failed.\n");	    return SECFailure;	}    }    PK11_FreeSlot(cryptoSlot);    PK11_FreeSlot(keySlot);    return SECSuccess;}void WriteItOut (void *arg, const char *buf, unsigned long len){    PRFileDesc *fileDesc = (PRFileDesc*)arg;    PR_Write(fileDesc, (void*)buf, len);}SECItemGetRandomBitString(void){#define NUM_BITS     800#define BITS_IN_BYTE 8    SECItem bitString;    int numBytes = NUM_BITS/BITS_IN_BYTE;    unsigned char *bits = PORT_ZNewArray(unsigned char, numBytes);    RNGContext *rng;    rng = RNG_CreateContext();    RNG_GenerateRandomBytes(rng, (void*)bits, numBytes);    RNG_DestroyContext(rng, PR_TRUE);    bitString.data = bits;    bitString.len = NUM_BITS;    bitString.type = siBuffer;    return bitString;}CRMFCertExtCreationInfo*GetExtensions(void){    CRMFCertExtCreationInfo *extInfo;    CRMFCertExtension *currExt;    CRMFCertExtension *extension;    SECItem data;    PRBool prFalse = PR_FALSE;    unsigned char keyUsage[4];    data.len = 4;    data.data = keyUsage;    keyUsage[0] = 0x03;    keyUsage[1] = 0x02;    keyUsage[2] = 0x07;    keyUsage[3] = KU_DIGITAL_SIGNATURE;    extension = CRMF_CreateCertExtension(SEC_OID_X509_KEY_USAGE,prFalse,					 &data);    extInfo = PORT_ZNew(CRMFCertExtCreationInfo);    extInfo->numExtensions = 1;    extInfo->extensions = PORT_ZNewArray(CRMFCertExtension*, 1);    extInfo->extensions[0] = extension;    return extInfo;}voidFreeExtInfo(CRMFCertExtCreationInfo *extInfo){    int i;        for (i=0; i<extInfo->numExtensions; i++) {        CRMF_DestroyCertExtension(extInfo->extensions[i]);    }    PORT_Free(extInfo->extensions);    PORT_Free(extInfo);}intCreateCertRequest (CRMFCertRequest **inCertReq, SECKEYPrivateKey **privKey,		   SECKEYPublicKey **pubKey){    long serialNumber;    long version = 3;    char *issuerStr = PORT_Strdup ("CN=Javi's CA Shack, O=Information Systems");    char *subjectStr = PORT_Strdup ("CN=Javi's CA Shack ID, O=Engineering, "				    "C=US");    CRMFCertRequest *certReq;    SECAlgorithmID * algID;    CERTName *issuer, *subject;    CRMFValidityCreationInfo validity;    CERTSubjectPublicKeyInfo *spki;    SECStatus rv;    SECOidTag tag, tag2;    SECItem issuerUID, subjectUID;    CRMFCertExtCreationInfo *extInfo;    CRMFEncryptedKey  *encKey;    CERTCertificate *caCert;    CRMFPKIArchiveOptions *pkiArchOpt;      *inCertReq = NULL;    certReq = CRMF_CreateCertRequest(0x0ff02345);    if (certReq == NULL) {        printf ("Could not initialize a certificate request.\n");	return 1;    }    rv = CRMF_CertRequestSetTemplateField (certReq, crmfVersion, (void*)(&version));    if (rv != SECSuccess) {        printf("Could not add the version number to the "	       "Certificate Request.\n");	CRMF_DestroyCertRequest(certReq);	return 2;    }    if (get_serial_number(&serialNumber) != SECSuccess) {        printf ("Could not generate a serial number for cert request.\n");	CRMF_DestroyCertRequest(certReq);	return 3;    }    rv = CRMF_CertRequestSetTemplateField (certReq, crmfSerialNumber, 				      (void*)(&serialNumber));    if (rv != SECSuccess) {        printf ("Could not add serial number to certificate template\n.");	CRMF_DestroyCertRequest(certReq);	return 4;    }        issuer = CERT_AsciiToName(issuerStr);    if (issuer == NULL) {        printf ("Could not create CERTName structure from %s.\n", issuerStr);	CRMF_DestroyCertRequest(certReq);	return 5;    }    rv = CRMF_CertRequestSetTemplateField (certReq, crmfIssuer, (void*) issuer);    PORT_Free(issuerStr);    CERT_DestroyName(issuer);    if (rv != SECSuccess) {        printf ("Could not add issuer to cert template\n");	CRMF_DestroyCertRequest(certReq);	return 6;    }    subject = CERT_AsciiToName(subjectStr);    if (subject == NULL) {        printf ("Could not create CERTName structure from %s.\n", subjectStr);	CRMF_DestroyCertRequest(certReq);	return 7;    }    PORT_Free(subjectStr);    rv = CRMF_CertRequestSetTemplateField (certReq, crmfSubject, (void*)subject);    if (rv != SECSuccess) {        printf ("Could not add subject to cert template\n");	CRMF_DestroyCertRequest(certReq);	return 8;    }    CERT_DestroyName(subject);    algID =    SEC_PKCS5CreateAlgorithmID (SEC_OID_PKCS5_PBE_WITH_SHA1_AND_DES_CBC,			       NULL, 1);    if (algID == NULL) {        printf ("Couldn't create algorithm ID\n");	CRMF_DestroyCertRequest(certReq);	return 9;    }    rv = CRMF_CertRequestSetTemplateField(certReq, crmfSigningAlg, (void*)algID);    SECOID_DestroyAlgorithmID(algID, PR_TRUE);    if (rv != SECSuccess) {        printf ("Could not add the signing algorithm to the cert template.\n");	CRMF_DestroyCertRequest(certReq);	return 10;    }    validity.notBefore = &notBefore;    validity.notAfter  = NULL;    notBefore = PR_Now();    rv = CRMF_CertRequestSetTemplateField(certReq, crmfValidity,(void*)(&validity));    if (rv != SECSuccess) {        printf ("Could not add validity to cert template\n");	CRMF_DestroyCertRequest(certReq);	return 11;    }    spki = GetSubjectPubKeyInfo(privKey, pubKey);    if (spki == NULL) {        printf ("Could not create a Subject Public Key Info to add\n");	CRMF_DestroyCertRequest(certReq);	return 12;    }    rv = CRMF_CertRequestSetTemplateField(certReq, crmfPublicKey, (void*)spki);    SECKEY_DestroySubjectPublicKeyInfo(spki);    if (rv != SECSuccess) {        printf ("Could not add the public key to the template\n");	CRMF_DestroyCertRequest(certReq);	return 13;    }        caCert =       CERT_FindCertByNickname(CERT_GetDefaultCertDB(), 			      caCertName);    if (caCert == NULL) {        printf ("Could not find the certificate for %s\n", caCertName);        CRMF_DestroyCertRequest(certReq);	return 50;    }    issuerUID = GetRandomBitString();    subjectUID = GetRandomBitString();    CRMF_CertRequestSetTemplateField(certReq,crmfIssuerUID,  (void*)&issuerUID);    CRMF_CertRequestSetTemplateField(certReq,crmfSubjectUID, (void*)&subjectUID);    PORT_Free(issuerUID.data);    PORT_Free(subjectUID.data);    extInfo = GetExtensions();    CRMF_CertRequestSetTemplateField(certReq, crmfExtension, (void*)extInfo);    FreeExtInfo(extInfo);    encKey = CRMF_CreateEncryptedKeyWithEncryptedValue(*privKey, caCert);    CERT_DestroyCertificate(caCert);    if (encKey == NULL) {        printf ("Could not create Encrypted Key with Encrypted Value.\n");	return 14;    }    pkiArchOpt = CRMF_CreatePKIArchiveOptions(crmfEncryptedPrivateKey, encKey);    CRMF_DestroyEncryptedKey(encKey);    if (pkiArchOpt == NULL) {        printf ("Could not create PKIArchiveOptions.\n");	return 15;    }    rv  = CRMF_CertRequestSetPKIArchiveOptions(certReq, pkiArchOpt);    CRMF_DestroyPKIArchiveOptions(pkiArchOpt);    if (rv != SECSuccess) {        printf ("Could not add the PKIArchiveControl to Cert Request.\n");	return 16;    }    *inCertReq = certReq;    return 0;}int Encode (CRMFCertReqMsg *inCertReq, 	CRMFCertReqMsg *secondReq, char *configdir){   #define PATH_LEN  150#define CRMF_FILE "CertReqMessages.der"    char filePath[PATH_LEN];    PRFileDesc *fileDesc;    SECStatus rv;    int irv = 0;    CRMFCertReqMsg *msgArr[3];    CRMFCertReqMsg *newMsg;    PR_snprintf(filePath, PATH_LEN, "%s/%s", configdir, CRMF_FILE);    fileDesc = PR_Open (filePath, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 			0666);    if (fileDesc == NULL) {        printf ("Could not open file %s\n", filePath);	irv = 14;	goto finish;    }/*    rv = CRMF_EncodeCertReqMsg (inCertReq, WriteItOut, (void*)fileDesc);*/    msgArr[0] = inCertReq;    msgArr[1] = secondReq;    msgArr[2] = NULL;    rv = CRMF_EncodeCertReqMessages(msgArr, WriteItOut, (void*)fileDesc);    if (rv != SECSuccess) {        printf ("An error occurred while encoding.\n");	irv = 15;	goto finish;    } finish:    PR_Close(fileDesc);    return irv;}intAddProofOfPossession(CRMFCertReqMsg *certReqMsg, SECKEYPrivateKey *privKey,		     SECKEYPublicKey *pubKey, CRMFPOPChoice inPOPChoice){    switch(inPOPChoice){    case crmfSignature:

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?