tor  0.4.0.0-alpha-dev
aes_nss.c
Go to the documentation of this file.
1 /* Copyright (c) 2001, Matej Pfajfar.
2  * Copyright (c) 2001-2004, Roger Dingledine.
3  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4  * Copyright (c) 2007-2018, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
12 #include "orconfig.h"
13 #include "lib/crypt_ops/aes.h"
16 #include "lib/log/util_bug.h"
17 
18 DISABLE_GCC_WARNING(strict-prototypes)
19 #include <pk11pub.h>
20 #include <secerr.h>
21 ENABLE_GCC_WARNING(strict-prototypes)
22 
23 aes_cnt_cipher_t *
24 aes_new_cipher(const uint8_t *key, const uint8_t *iv,
25  int key_bits)
26 {
27  const CK_MECHANISM_TYPE ckm = CKM_AES_CTR;
28  SECItem keyItem = { .type = siBuffer,
29  .data = (unsigned char *)key,
30  .len = (key_bits / 8) };
31  CK_AES_CTR_PARAMS params;
32  params.ulCounterBits = 128;
33  memcpy(params.cb, iv, 16);
34  SECItem ivItem = { .type = siBuffer,
35  .data = (unsigned char *)&params,
36  .len = sizeof(params) };
37  PK11SlotInfo *slot = NULL;
38  PK11SymKey *keyObj = NULL;
39  SECItem *ivObj = NULL;
40  PK11Context *result = NULL;
41 
42  slot = PK11_GetBestSlot(ckm, NULL);
43  if (!slot)
44  goto err;
45 
46  keyObj = PK11_ImportSymKey(slot, ckm, PK11_OriginUnwrap,
47  CKA_ENCRYPT, &keyItem, NULL);
48  if (!keyObj)
49  goto err;
50 
51  ivObj = PK11_ParamFromIV(ckm, &ivItem);
52  if (!ivObj)
53  goto err;
54 
55  PORT_SetError(SEC_ERROR_IO);
56  result = PK11_CreateContextBySymKey(ckm, CKA_ENCRYPT, keyObj, ivObj);
57 
58  err:
59  memwipe(&params, 0, sizeof(params));
60  if (ivObj)
61  SECITEM_FreeItem(ivObj, PR_TRUE);
62  if (keyObj)
63  PK11_FreeSymKey(keyObj);
64  if (slot)
65  PK11_FreeSlot(slot);
66 
67  tor_assert(result);
68  return (aes_cnt_cipher_t *)result;
69 }
70 
71 void
72 aes_cipher_free_(aes_cnt_cipher_t *cipher)
73 {
74  if (!cipher)
75  return;
76  PK11_DestroyContext((PK11Context*) cipher, PR_TRUE);
77 }
78 
79 void
80 aes_crypt_inplace(aes_cnt_cipher_t *cipher, char *data_, size_t len_)
81 {
82  tor_assert(len_ <= INT_MAX);
83 
84  SECStatus s;
85  PK11Context *ctx = (PK11Context*)cipher;
86  unsigned char *data = (unsigned char *)data_;
87  int len = (int) len_;
88  int result_len = 0;
89 
90  s = PK11_CipherOp(ctx, data, &result_len, len, data, len);
91  tor_assert(s == SECSuccess);
92  tor_assert(result_len == len);
93 }
94 
95 int
96 evaluate_evp_for_aes(int force_value)
97 {
98  (void)force_value;
99  return 0;
100 }
101 
102 int
103 evaluate_ctr_for_aes(void)
104 {
105  return 0;
106 }
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
Common functions for cryptographic routines.
tor_assert(buffer)
Headers for aes.c.
Macros to manage assertions, fatal and non-fatal.
Headers for crypto_nss_mgt.c.