testcrmf.c

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

C
1,528
字号
      CRMF_CertReqMsgSetSignaturePOP(certReqMsg, privKey, pubKey, NULL, NULL, 				     NULL);      break;    case crmfRAVerified:      CRMF_CertReqMsgSetRAVerifiedPOP(certReqMsg);      break;    case crmfKeyEncipherment:      CRMF_CertReqMsgSetKeyEnciphermentPOP(certReqMsg,					   crmfSubsequentMessage, 					   crmfChallengeResp, NULL);      break;    case crmfKeyAgreement:      {	SECItem pendejo;	unsigned char lame[] = { 0xf0, 0x0f, 0xf0, 0x0f, 0xf0 };	pendejo.data = lame;	pendejo.len  = 5;		CRMF_CertReqMsgSetKeyAgreementPOP(certReqMsg, crmfThisMessage, 					  crmfNoSubseqMess, &pendejo);      }      break;    default:      return 1;    }    return 0;}#define BUFF_SIZE  150intDecode(char *configdir){    char           filePath[PATH_LEN];    unsigned char  buffer[BUFF_SIZE];    char          *asn1Buff;    PRFileDesc    *fileDesc;    PRInt32          fileLen = 0;    PRInt32          bytesRead;    CRMFCertReqMsg  *certReqMsg;    CRMFCertRequest *certReq;    CRMFGetValidity validity= {NULL, NULL};    CRMFCertReqMessages *certReqMsgs;    int numMsgs, i;    long lame;    PR_snprintf(filePath, PATH_LEN, "%s/%s", configdir, CRMF_FILE);    fileDesc = PR_Open(filePath, PR_RDONLY, 0644);    while (1) {        bytesRead = PR_Read(fileDesc, buffer, BUFF_SIZE);	if (bytesRead <= 0) break;	fileLen += bytesRead;    }    if (bytesRead < 0) {        printf ("Error while getting the length of the file %s\n", filePath);	return 200;    }        PR_Close(fileDesc);    fileDesc = PR_Open(filePath, PR_RDONLY, 0644);    asn1Buff = PORT_ZNewArray(char, fileLen);    bytesRead = PR_Read(fileDesc, asn1Buff, fileLen);    if (bytesRead != fileLen) {        printf ("Error while reading in the contents of %s\n", filePath);	return 201;    }    /*certReqMsg = CRMF_CreateCertReqMsgFromDER(asn1Buff, fileLen);    if (certReqMsg == NULL) {        printf ("Error while decoding the CertReqMsg\n");	return 202;    }    certReq = CRMF_CertReqMsgGetCertRequest(certReqMsg);*/    certReqMsgs = CRMF_CreateCertReqMessagesFromDER(asn1Buff, fileLen);    if (certReqMsgs == NULL) {        printf ("Error decoding CertReqMessages.\n");	return 202;    }    numMsgs = CRMF_CertReqMessagesGetNumMessages(certReqMsgs);    if (numMsgs <= 0) {        printf ("WARNING: The DER contained %d messages.\n", numMsgs);    }    for (i=0; i < numMsgs; i++) {        certReqMsg = CRMF_CertReqMessagesGetCertReqMsgAtIndex(certReqMsgs, i);	if (certReqMsg == NULL) {	    printf ("ERROR: Could not access the message at index %d of %s\n",		    i, filePath);	}	CRMF_CertReqMsgGetID(certReqMsg, &lame);	certReq = CRMF_CertReqMsgGetCertRequest(certReqMsg);	CRMF_CertRequestGetCertTemplateValidity(certReq, &validity);	CRMF_DestroyGetValidity(&validity);	CRMF_DestroyCertRequest(certReq);	CRMF_DestroyCertReqMsg(certReqMsg);    }    CRMF_DestroyCertReqMessages(certReqMsgs);    PORT_Free(asn1Buff);    return 0;}voidGetBitsFromFile(char *filePath, SECItem *fileBits){    PRFileDesc *fileDesc;    int         bytesRead, fileLen=0;    char        buffer[BUFF_SIZE], *asn1Buf;    fileDesc = PR_Open(filePath, PR_RDONLY, 0644);    while (1) {        bytesRead = PR_Read(fileDesc, buffer, BUFF_SIZE);	if (bytesRead <= 0) break;	fileLen += bytesRead;    }    if (bytesRead < 0) {        printf ("Error while getting the length of file %s.\n", filePath);	goto loser;    }    PR_Close(fileDesc);        fileDesc = PR_Open(filePath, PR_RDONLY, 0644);    asn1Buf = PORT_ZNewArray(char, fileLen);    if (asn1Buf == NULL) {        printf ("Out of memory in function GetBitsFromFile\n");        goto loser;    }    bytesRead = PR_Read(fileDesc, asn1Buf, fileLen);    if (bytesRead != fileLen) {        printf ("Error while reading the contents of %s\n", filePath);	goto loser;    }    fileBits->data = (unsigned char*)asn1Buf;    fileBits->len  = fileLen;    return; loser:    if (asn1Buf) {        PORT_Free(asn1Buf);    }    fileBits->data = NULL;    fileBits->len  = 0;} intDecodeCMMFCertRepContent(char *derFile){    int         fileLen=0;    char       *asn1Buf;    SECItem     fileBits;    CMMFCertRepContent *certRepContent;    GetBitsFromFile(derFile, &fileBits);    if (fileBits.data == NULL) {        printf("Could not get bits from file %s\n", derFile);        return 304;    }    asn1Buf = (char*)fileBits.data;    fileLen = fileBits.len;    certRepContent = CMMF_CreateCertRepContentFromDER(db, asn1Buf, fileLen);    if (certRepContent == NULL) {        printf ("Error while decoding %s\n", derFile);	return 303;    }    CMMF_DestroyCertRepContent(certRepContent);    PORT_Free(asn1Buf);    return 0;}intDoCMMFStuff(char *configdir){    CMMFCertResponse   *certResp=NULL, *certResp2=NULL, *certResponses[3];    CMMFCertRepContent *certRepContent=NULL;    CERTCertificate    *cert=NULL, *caCert=NULL;    CERTCertList       *list=NULL;    PRFileDesc         *fileDesc=NULL;    char                filePath[PATH_LEN];    int                 rv = 0;    long                random;    CMMFKeyRecRepContent       *repContent=NULL;    SECKEYPrivateKey           *privKey = NULL;    SECKEYPublicKey *caPubKey;    SECStatus        srv;    SECItem          fileBits;        certResp = CMMF_CreateCertResponse(0xff123);    CMMF_CertResponseSetPKIStatusInfoStatus(certResp, cmmfGranted);    cert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), personalCert);    if (cert == NULL) {        printf ("Could not find the certificate for %s\n", personalCert);        rv = 416;        goto finish;    }     CMMF_CertResponseSetCertificate(certResp, cert);    certResp2 = CMMF_CreateCertResponse(0xff122);    CMMF_CertResponseSetPKIStatusInfoStatus(certResp2, cmmfGranted);    CMMF_CertResponseSetCertificate(certResp2, cert);        certResponses[0] = certResp;    certResponses[1] = NULL;    certResponses[2] = NULL;    certRepContent = CMMF_CreateCertRepContent();    CMMF_CertRepContentSetCertResponses(certRepContent, certResponses, 1);    list = CERT_GetCertChainFromCert(cert, PR_Now(), certUsageEmailSigner);    CMMF_CertRepContentSetCAPubs(certRepContent, list);    PR_snprintf(filePath, PATH_LEN, "%s/%s", configdir, "CertRepContent.der");    fileDesc = PR_Open (filePath, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 			0666);    if (fileDesc == NULL) {        printf ("Could not open file %s\n", filePath);	rv = 400;	goto finish;    }        srv = CMMF_EncodeCertRepContent(certRepContent, WriteItOut, 				    (void*)fileDesc);    PORT_Assert (srv == SECSuccess);    PR_Close(fileDesc);    rv = DecodeCMMFCertRepContent(filePath);    if (rv != 0) {        goto finish;    }    random = 0xa4e7;    caCert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), 				     caCertName);    if (caCert == NULL) {        printf ("Could not get the certifcate for %s\n", caCertName);	rv = 411;	goto finish;    }    repContent = CMMF_CreateKeyRecRepContent();    if (repContent == NULL) {        printf ("Could not allocate a CMMFKeyRecRepContent structure\n");	rv = 407;	goto finish;    }    srv = CMMF_KeyRecRepContentSetPKIStatusInfoStatus(repContent, 						      cmmfGrantedWithMods);    if (srv != SECSuccess) {        printf ("Error trying to set PKIStatusInfo for "		"CMMFKeyRecRepContent.\n");	rv = 406;	goto finish;    }    srv = CMMF_KeyRecRepContentSetNewSignCert(repContent, cert);    if (srv != SECSuccess) {        printf ("Error trying to set the new signing certificate for "		"key recovery\n");	rv = 408;	goto finish;    }    srv = CMMF_KeyRecRepContentSetCACerts(repContent, list);    if (srv != SECSuccess) {        printf ("Errory trying to add the list of CA certs to the "		"CMMFKeyRecRepContent structure.\n");	rv = 409;	goto finish;    }    privKey = PK11_FindKeyByAnyCert(cert, NULL);    if (privKey == NULL) {        printf ("Could not get the private key associated with the\n"		"certificate %s\n", personalCert);	rv = 410;	goto finish;    }    caPubKey = CERT_ExtractPublicKey(caCert);    if (caPubKey == NULL) {        printf ("Could not extract the public from the "		"certificate for \n%s\n", caCertName);	rv = 412;	goto finish;    }    CERT_DestroyCertificate(caCert);    caCert = NULL;    srv = CMMF_KeyRecRepContentSetCertifiedKeyPair(repContent, cert, privKey,						   caPubKey);    SECKEY_DestroyPrivateKey(privKey);    SECKEY_DestroyPublicKey(caPubKey);    if (srv != SECSuccess) {        printf ("Could not set the Certified Key Pair\n");	rv = 413;	goto finish;    }    PR_snprintf(filePath, PATH_LEN, "%s/%s", configdir, 		"KeyRecRepContent.der");    fileDesc = PR_Open (filePath, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 			0666);    if (fileDesc == NULL) {        printf ("Could not open file %s\n", filePath);	rv = 414;	goto finish;    }        srv = CMMF_EncodeKeyRecRepContent(repContent, WriteItOut, 				      (void*)fileDesc);    PORT_Assert (srv == SECSuccess);    PR_Close(fileDesc);    CMMF_DestroyKeyRecRepContent(repContent);    GetBitsFromFile(filePath, &fileBits);    repContent =         CMMF_CreateKeyRecRepContentFromDER(db, (const char *) fileBits.data,					   fileBits.len);    if (repContent == NULL) {        printf ("ERROR: CMMF_CreateKeyRecRepContentFromDER failed on file:\n"		"\t%s\n", filePath);	rv = 415;	goto finish;    } finish:    if (repContent) {        CMMF_DestroyKeyRecRepContent(repContent);    }    if (cert) {        CERT_DestroyCertificate(cert);    }    if (list) {        CERT_DestroyCertList(list);    }    if (certResp) {        CMMF_DestroyCertResponse(certResp);    }    if (certResp2) {        CMMF_DestroyCertResponse(certResp2);    }    if (certRepContent) {        CMMF_DestroyCertRepContent(certRepContent);    }    return rv;}static CK_MECHANISM_TYPEmapWrapKeyType(KeyType keyType){    switch (keyType) {    case rsaKey:        return CKM_RSA_PKCS;    default:        break;    }    return CKM_INVALID_MECHANISM;} #define KNOWN_MESSAGE_LENGTH 20 /*160 bits*/intDoKeyRecovery(char *configdir, SECKEYPrivateKey *privKey){    SECKEYPublicKey *pubKey;    PK11SlotInfo    *slot;    CK_OBJECT_HANDLE id;    CK_MECHANISM     mech = { CKM_INVALID_MECHANISM, NULL, 0};    unsigned char *known_message = (unsigned char*)"Known Crypto Message";    unsigned char  plaintext[KNOWN_MESSAGE_LENGTH];    char filePath[PATH_LEN];    CK_RV            crv;    unsigned char   *ciphertext;    CK_ULONG         max_bytes_encrypted, bytes_encrypted;    unsigned char   *text_compared;    CK_ULONG         bytes_compared, bytes_decrypted;    SECKEYPrivateKey *unwrappedPrivKey, *caPrivKey;    CMMFKeyRecRepContent *keyRecRep;    SECStatus rv;    CERTCertificate *caCert, *myCert;    SECKEYPublicKey *caPubKey;    PRFileDesc *fileDesc;    SECItem fileBits, nickname;    CMMFCertifiedKeyPair *certKeyPair;    /*caCert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), 				     caCertName);*/    myCert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), personalCert);    if (myCert == NULL) {        printf ("Could not find the certificate for %s\n", personalCert);        return 700;    }    caCert = CERT_FindCertByNickname(CERT_GetDefaultCertDB(), 				     recoveryEncrypter);    if (caCert == NULL) {        printf ("Could not find the certificate for %s\n", recoveryEncrypter);        return 701;    }    caPubKey = CERT_ExtractPublicKey(caCert);    pubKey = SECKEY_ConvertToPublicKey(privKey);    max_bytes_encrypted = PK11_GetPrivateModulusLen(privKey);    slot = PK11_GetBestSlot(mapWrapKeyType(privKey->keyType), NULL);    id = PK11_ImportPublicKey(slot, pubKey, PR_FALSE);    switch(privKey->keyType) {    case rsaKey:        mech.mechanism = CKM_RSA_PKCS;	break;    case dsaKey:        mech.mechanism = CKM_DSA;	break;    case dhKey:        mech.mechanism = CKM_DH_PKCS_DERIVE;	break;    default:        printf ("Bad Key type in key recovery.\n");	return 512;    }    PK11_EnterSlotMonitor(slot);    crv = PK11_GETTAB(slot)->C_EncryptInit(slot->session, &mech, id);    if (crv != CKR_OK) {        PK11_ExitSlotMonitor(slot);	PK11_FreeSlot(slot);	printf ("C_EncryptInit failed in KeyRecovery\n");	return 500;    }    ciphertext = PORT_NewArray(unsigned char, max_bytes_encrypted);    if (ciphertext == NULL) {        PK11_ExitSlotMonitor(slot);	PK11_FreeSlot(slot);	printf ("Could not allocate memory for ciphertext.\n");	return 501;    }    bytes_encrypted = max_bytes_encrypted;    crv = PK11_GETTAB(slot)->C_Encrypt(slot->session, 				       known_message,				       KNOWN_MESSAGE_LENGTH,				       ciphertext,				       &bytes_encrypted);    PK11_ExitSlotMonitor(slot);    PK11_FreeSlot(slot);    if (crv != CKR_OK) {       PORT_Free(ciphertext);       return 502;    }    /* Always use the smaller of these two values . . . */    bytes_compared = ( bytes_encrypted > KNOWN_MESSAGE_LENGTH )                      ? KNOWN_MESSAGE_LENGTH                      : bytes_encrypted;     /* If there was a failure, the plaintext */    /* goes at the end, therefore . . .      */    text_compared = ( bytes_encrypted > KNOWN_MESSAGE_LENGTH )                    ? (ciphertext + bytes_encrypted -		       KNOWN_MESSAGE_LENGTH )                     : ciphertext;      keyRecRep = CMMF_CreateKeyRecRepContent();    if (keyRecRep == NULL) {        PORT_Free(ciphertext);	PK11_FreeSlot(slot);	CMMF_DestroyKeyRecRepContent(keyRecRep);	printf ("Could not allocate a CMMFKeyRecRepContent structre.\n");	return 503;    }    rv = CMMF_KeyRecRepContentSetPKIStatusInfoStatus(keyRecRep,						     cmmfGranted);    if (rv != SECSuccess) {        PORT_Free(ciphertext);	PK11_FreeSlot(slot);	CMMF_DestroyKeyRecRepContent(keyRecRep);	printf ("Could not set the status for the KeyRecRepContent\n");	return 504;    }    /* The myCert here should correspond to the certificate corresponding     * to the private key, but for this test any certificate will do.     */    rv = CMMF_KeyRecRepContentSetCertifiedKeyPair(keyRecRep, myCert,						  privKey, caPubKey);    if (rv != SECSuccess) {        PORT_Free(ciphertext);	PK11_FreeSlot(slot);	CMMF_DestroyKeyRecRepContent(keyRecRep);	printf ("Could not set the Certified Key Pair\n");	return 505;    }    PR_snprintf(filePath, PATH_LEN, "%s/%s", configdir, 		"KeyRecRepContent.der");    fileDesc = PR_Open (filePath, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 			0666);    if (fileDesc == NULL) {        PORT_Free(ciphertext);	PK11_FreeSlot(slot);	CMMF_DestroyKeyRecRepContent(keyRecRep);        printf ("Could not open file %s\n", filePath);	return 506;    }    rv = CMMF_EncodeKeyRecRepContent(keyRecRep, WriteItOut, fileDesc);    CMMF_DestroyKeyRecRepContent(keyRecRep);    PR_Close(fileDesc);    if (rv != SECSuccess) {        PORT_Free(ciphertext);	PK11_FreeSlot(slot);	printf ("Error while encoding CMMFKeyRecRepContent\n");	return 507;    }    GetBitsFromFile(filePath, &fileBits);    if (fileBits.data == NULL) {        PORT_Free(ciphertext);	PK11_FreeSlot(slot);        printf ("Could not get the bits from file %s\n", filePath);	return 508;    }    keyRecRep =         CMMF_CreateKeyRecRepContentFromDER(db,(const char*)fileBits.data,					   fileBits.len);    if (keyRecRep == NULL) {        printf ("Could not decode the KeyRecRepContent in file %s\n", 		filePath);	PORT_Free(ciphertext);	PK11_FreeSlot(slot);	return 509;    }

⌨️ 快捷键说明

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