Created
September 11, 2018 07:08
-
-
Save rhelmer/e4e3b3babd17b90acbc1781dc8c9ac94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <limits.h> | |
#include <nspr/prinit.h> | |
#include <nss/nss.h> | |
#include <nss/pk11pub.h> | |
#define ASSERT(a) (assert((a) != NULL)) | |
#define KEYLEN (128/8) | |
static SECStatus | |
PRG_get_bytes(PK11Context *ctx, unsigned char* bytes, size_t len) | |
{ | |
unsigned char in[len]; | |
memset(in, 0, len); | |
int outlen; | |
SECStatus rv = PK11_CipherOp(ctx, bytes, &outlen, len, in, len); | |
return (rv != SECSuccess || (size_t)outlen != len) ? SECFailure : SECSuccess; | |
} | |
int | |
main(void) | |
{ | |
PK11SlotInfo* slot; | |
PK11SymKey* key; | |
PK11Context* ctx; | |
NSSInitContext* globalctx = NSS_InitContext("", "", "", "", NULL, | |
NSS_INIT_READONLY | NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | | |
NSS_INIT_FORCEOPEN | NSS_INIT_NOROOTINIT); | |
const CK_MECHANISM_TYPE cipher = CKM_AES_CTR; | |
ASSERT(slot = PK11_GetInternalSlot()); | |
// Use arbitrary bytes for the AES key | |
unsigned char key_bytes[KEYLEN]; | |
for (int i = 0; i < KEYLEN; i++) { | |
key_bytes[i] = i; | |
} | |
SECItem keyItem = { siBuffer, key_bytes, KEYLEN }; | |
// The IV can be all zeros since we only encrypt once with | |
// each AES key. | |
CK_AES_CTR_PARAMS param = { 128, {} }; | |
SECItem paramItem = { siBuffer, (void*)¶m, sizeof(CK_AES_CTR_PARAMS) }; | |
ASSERT(key = PK11_ImportSymKey(slot, cipher, PK11_OriginUnwrap, | |
CKA_ENCRYPT, &keyItem, NULL)); | |
ASSERT(ctx = PK11_CreateContextBySymKey(cipher, CKA_ENCRYPT, key, ¶mItem)); | |
unsigned char outbuf[128]; | |
assert(PRG_get_bytes(ctx, outbuf, 7) == SECSuccess); | |
assert(PRG_get_bytes(ctx, outbuf, 17) == SECSuccess); | |
PK11_FreeSymKey(key); | |
PK11_FreeSlot(slot); | |
PK11_DestroyContext(ctx, PR_TRUE); | |
NSS_ShutdownContext(globalctx); | |
PR_Cleanup(); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment