blob: 04907e8ed24acaacc3a5b1f758f6cd41469783f8 [file] [log] [blame]
Jim Schaad6b29f602015-06-08 20:42:30 -07001#include "cose.h"
2#include "configure.h"
3#include "cose_int.h"
4#include "crypto.h"
5
6#if USE_BCRYPT
7
8#include <Windows.h>
9
10bool AES_CCM_Encrypt(COSE_Encrypt * pcose, int TSize, int LSize, int KSize, byte * pbAuthData, int cbAuthData)
11{
12 NTSTATUS err;
13 BCRYPT_ALG_HANDLE hAlg = NULL;
14 BCRYPT_KEY_DATA_BLOB_HEADER * pHdr = NULL;
15 BCRYPT_KEY_HANDLE hKey = NULL;
16 BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO authInfo = { 0 };
17 byte rgbTag[16];
18 int cbOut;
19 byte * pbOut = NULL;
20
21 err = BCryptOpenAlgorithmProvider(&hAlg, "AES_CCM", NULL, 0);
22 if (err != 0) {
23 error:
24 if (pbOut != NULL) free(pbOut);
25 if (pHdr != NULL) free(pHdr);
26 if (hKey != NULL) BCryptDestroyKey(hKey);
27 if (hAlg != NULL) BCryptCloseAlgorithmProvider(hAlg, 0);
28 return false;
29 }
30
31 pHdr = (BCRYPT_KEY_DATA_BLOB_HEADER *)malloc(sizeof(*pHdr) + KSize / 8);
32 if (pHdr == NULL) goto error;
33 pHdr->dwMagic = BCRYPT_KEY_DATA_BLOB_MAGIC;
34 pHdr->dwVersion = BCRYPT_KEY_DATA_BLOB_VERSION1;
35 pHdr->cbKeyData = KSize / 8;
36 memcpy(&pHdr[1], pcose->pbKey, pcose->cbKey);
37
38 err = BCryptImportKey(hAlg, NULL, BCRYPT_KEY_DATA_BLOB, &hKey, NULL, 0, pHdr, (sizeof(*pHdr) + KSize / 8), 0);
39 if (err != 0) goto error;
40
41 BCRYPT_INIT_AUTH_MODE_INFO(authInfo);
42 authInfo.pbNonce = pcose->pbIV;
43 authInfo.cbNonce = pcose->cbIV;
44 authInfo.pbAuthData = pbAuthData;
45 authInfo.cbAuthData = cbAuthData;
46 authInfo.pbTag = rgbTag;
47 authInfo.cbTag = TSize / 8;
48 authInfo.pbMacContext = NULL;
49
50 cbOut = pcose->cbContent + TSize / 8;
51 pbOut = (byte *)malloc(cbOut);
52 if (pbOut == NULL) goto error;
53
54 err = BCryptEncrypt(hKey, pcose->pbContent, pcose->cbContent, &authInfo, NULL, 0, pbOut, cbOut, 0, 0);
55 if (err != 0) goto error;
56
57 memcpy(&pbOut[pcose->cbContent], rgbTag, TSize / 8);
58
59 cn_cbor_mapput_int(pcose->m_message.m_cbor, COSE_Header_Ciphertext, cn_cbor_data_create(pbOut, cbOut, NULL), NULL);
60
61 return true;
62}
63
64#endif // USE_BCRYPT