defensive-coding-guide/modules/ROOT/examples/Features-HSM-NSS.adoc
2022-01-13 20:42:40 +01:00

56 lines
1.5 KiB
Text

SECStatus rv;
CERTCertificate *cert = NULL;
SECKEYPrivateKey *pvtkey = NULL;
SECItem signature = { siBuffer, NULL, 0 };
SECOidTag algTag;
int r = 1;
unsigned char buf[] = "test data to sign";
const char *cert_name;
unsigned i;
if (argc < 3) {
fprintf(stderr, "usage: %s [cert name] [PIN]\n\n", argv[0]);
exit(1);
}
cert_name = argv[1];
pin = argv[2];
PK11_SetPasswordFunc(passwdcb);
NSS_InitializePRErrorTable();
rv = NSS_Init(".");
if (rv != SECSuccess) {
fprintf(stderr, "NSS initialization failed (err %d)\n", PR_GetError());
goto cleanup;
}
cert = PK11_FindCertFromNickname(cert_name, NULL);
if (cert == NULL) {
fprintf(stderr, "Couldn't find cert %s in NSS db (err %d: %s)\n",
cert_name, PR_GetError(), PORT_ErrorToString(PR_GetError()));
goto cleanup;
}
fprintf(stderr, "Buffer being signed = \n%s\n", buf);
pvtkey = PK11_FindKeyByAnyCert(cert, NULL);
if (pvtkey == NULL) {
fprintf(stderr, "Couldn't find private key for cert %s (err %d: %s)\n",
cert_name, PR_GetError(), PORT_ErrorToString(PR_GetError()));
goto cleanup;
}
/* get the algtag. Pick the default hash algorithm */
algTag = SEC_GetSignatureAlgorithmOidTag(pvtkey->keyType, SEC_OID_UNKNOWN);
fprintf(stderr, "Signing with alg = %s (%d)\n",
SECOID_FindOIDTagDescription(algTag), algTag);
rv = SEC_SignData(&signature, buf, sizeof(buf)-1, pvtkey, algTag);
if (rv != SECSuccess) {
fprintf(stderr, "sign with Private Key failed (err %d: %s)\n",
PR_GetError(), PORT_ErrorToString(PR_GetError()));
goto cleanup;
}