nsresult nsStreamCipher::InitWithIV_(nsIKeyObject *aKey, SECItem* aIV) { NS_ENSURE_ARG_POINTER(aKey); // Make sure we have a SYM_KEY. PRInt16 keyType; nsresult rv = aKey->GetType(&keyType); NS_ENSURE_SUCCESS(rv, rv); if (keyType != nsIKeyObject::SYM_KEY) return NS_ERROR_INVALID_ARG; if (mContext) PK11_DestroyContext(mContext, true /* free sub-objects */); // Get the PK11SymKey out of the key object and create the PK11Context. void* keyObj; rv = aKey->GetKeyObj(&keyObj); NS_ENSURE_SUCCESS(rv, rv); PK11SymKey *symkey = reinterpret_cast<PK11SymKey*>(keyObj); if (!symkey) return NS_ERROR_FAILURE; CK_MECHANISM_TYPE cipherMech = PK11_GetMechanism(symkey); SECItem *param = nullptr; // aIV may be null param = PK11_ParamFromIV(cipherMech, aIV); if (!param) return NS_ERROR_FAILURE; mContext = PK11_CreateContextBySymKey(cipherMech, CKA_ENCRYPT, symkey, param); SECITEM_FreeItem(param, true); // Something went wrong if mContext doesn't exist. if (!mContext) return NS_ERROR_FAILURE; // Everything went ok. mValue.Truncate(); return NS_OK; }
void genkey(int id) { PK11SlotInfo* slot = NULL; PK11SymKey* key = NULL; SECItem keyiditem; int keyid[1]; CK_MECHANISM_TYPE cipherMech; /* using CKM_AES_CBC_PAD mechanism for example */ cipherMech = CKM_AES_CBC_PAD; slot = PK11_GetInternalKeySlot(); /* slot = PK11_GetBestSlot(cipherMech, NULL); didn't work. * Error code: token is read-only. ?? */ if (slot == NULL) { fprintf(stderr, "Unable to find security device (err %d)\n", PR_GetError()); return; } keyid[0] = id; keyiditem.type = siBuffer; keyiditem.data = (void *)keyid; keyiditem.len = sizeof(keyid[0]); /* Note: keysize must be 0 for fixed key-length algorithms like DES. * Since we're using AES in this example, we're specifying * one of the valid keysizes (16, 24, 32) */ key = PK11_TokenKeyGen(slot, cipherMech, 0, 32 /*keysize*/, &keyiditem, PR_TRUE, 0); if (key == NULL) { fprintf(stderr, "PK11_TokenKeyGen failed (err %d)\n", PR_GetError()); PK11_FreeSlot(slot); return; } fprintf(stderr, "key length of generated key is %d\n", PK11_GetKeyLength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", PK11_GetMechanism(key), cipherMech); PK11_FreeSymKey(key); key = PK11_FindFixedKey(slot, cipherMech, &keyiditem, 0); if (key == NULL) { fprintf(stderr, "PK11_FindFixedKey failed (err %d)\n", PR_GetError()); PK11_FreeSlot(slot); return; } fprintf(stderr, "Found key!\n"); fprintf(stderr, "key length of generated key is %d\n", PK11_GetKeyLength(key)); fprintf(stderr, "mechanism of key is %d (asked for %d)\n", PK11_GetMechanism(key), cipherMech); PK11_FreeSymKey(key); PK11_FreeSlot(slot); }