Embedded SDK
Embedded SDK
cx_hkdf.c
Go to the documentation of this file.
1 #ifdef HAVE_HMAC
2 #include "cx_hkdf.h"
3 #include "cx_hash.h"
4 #include "cx_hmac.h"
5 #include "cx_ram.h"
6 
7 #include <string.h>
8 
9 // HMAC-Based Key Kerivation Function defined at https://tools.ietf.org/html/rfc5869
10 // Used to implement the EIP-2333 for BLS12-381 key generation
11 
12 void cx_hkdf_extract(const cx_md_t hash_id,
13  const unsigned char *ikm,
14  unsigned int ikm_len,
15  unsigned char *salt,
16  unsigned int salt_len,
17  unsigned char *prk)
18 {
19  cx_hmac_t *hmac_ctx;
20  const cx_hash_info_t *hash_info;
21  size_t md_len;
22 
23  hash_info = cx_hash_get_info(hash_id);
24  md_len = hash_info->output_size;
25 
26  hmac_ctx = &G_cx.hmac;
27 
28  if (salt == NULL) {
29  memset(hmac_ctx->key, 0, md_len);
30  salt = hmac_ctx->key;
31  salt_len = md_len;
32  }
33  if (cx_hmac_init(hmac_ctx, hash_id, salt, salt_len) != CX_OK
34  || cx_hmac_update(hmac_ctx, ikm, ikm_len) != CX_OK
35  || cx_hmac_final(hmac_ctx, prk, &md_len) != CX_OK) {
36  return;
37  }
38 }
39 
40 void cx_hkdf_expand(const cx_md_t hash_id,
41  const unsigned char *prk,
42  unsigned int prk_len,
43  unsigned char *info,
44  unsigned int info_len,
45  unsigned char *okm,
46  unsigned int okm_len)
47 {
48  unsigned char i;
49  unsigned int offset = 0;
50  unsigned char T[MAX_HASH_SIZE];
51  cx_hmac_t *hmac_ctx;
52  const cx_hash_info_t *hash_info;
53  size_t md_len;
54 
55  hash_info = cx_hash_get_info(hash_id);
56  md_len = hash_info->output_size;
57 
58  hmac_ctx = &G_cx.hmac;
59 
60  for (i = 1; okm_len > 0; i++) {
61  if (cx_hmac_init(hmac_ctx, hash_id, prk, prk_len) != CX_OK) {
62  return;
63  }
64  if (i > 1) {
65  if (cx_hmac_update(hmac_ctx, T, offset) != CX_OK) {
66  return;
67  }
68  }
69  if (cx_hmac_update(hmac_ctx, info, info_len) != CX_OK
70  || cx_hmac_update(hmac_ctx, &i, sizeof(i)) != CX_OK
71  || cx_hmac_final(hmac_ctx, T, &md_len) != CX_OK) {
72  return;
73  }
74 
75  offset = (okm_len < md_len) ? okm_len : md_len;
76  memcpy(okm + (i - 1) * md_len, T, offset);
77  okm_len -= offset;
78  }
79 }
80 #endif // HAVE_HMAC
void cx_hkdf_extract(const cx_md_t hash_id, const unsigned char *ikm, unsigned int ikm_len, unsigned char *salt, unsigned int salt_len, unsigned char *prk)
void cx_hkdf_expand(const cx_md_t hash_id, const unsigned char *prk, unsigned int prk_len, unsigned char *info, unsigned int info_len, unsigned char *okm, unsigned int okm_len)
union cx_u G_cx
Definition: cx_ram.c:21