3 * Copyright (c) 2013 Cozybit, Inc.
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
17 static const u8 zero[AES_BLOCK_SIZE];
20 static void dbl(u8 *pad)
24 carry = pad[0] & 0x80;
25 for (i = 0; i < AES_BLOCK_SIZE - 1; i++)
26 pad[i] = (pad[i] << 1) | (pad[i + 1] >> 7);
27 pad[AES_BLOCK_SIZE - 1] <<= 1;
29 pad[AES_BLOCK_SIZE - 1] ^= 0x87;
33 static void xor(u8 *a, const u8 *b)
37 for (i = 0; i < AES_BLOCK_SIZE; i++)
42 static void xorend(u8 *a, int alen, const u8 *b, int blen)
49 for (i = 0; i < blen; i++)
50 a[alen - blen + i] ^= b[i];
54 static void pad_block(u8 *pad, const u8 *addr, size_t len)
56 os_memset(pad, 0, AES_BLOCK_SIZE);
57 os_memcpy(pad, addr, len);
59 if (len < AES_BLOCK_SIZE)
64 static int aes_s2v(const u8 *key, size_t num_elem, const u8 *addr[],
67 u8 tmp[AES_BLOCK_SIZE], tmp2[AES_BLOCK_SIZE];
73 os_memcpy(tmp, zero, sizeof(zero));
74 tmp[AES_BLOCK_SIZE - 1] = 1;
75 return omac1_aes_128(key, tmp, sizeof(tmp), mac);
78 ret = omac1_aes_128(key, zero, sizeof(zero), tmp);
82 for (i = 0; i < num_elem - 1; i++) {
83 ret = omac1_aes_128(key, addr[i], len[i], tmp2);
90 if (len[i] >= AES_BLOCK_SIZE) {
91 buf = os_malloc(len[i]);
95 os_memcpy(buf, addr[i], len[i]);
96 xorend(buf, len[i], tmp, AES_BLOCK_SIZE);
97 ret = omac1_aes_128(key, buf, len[i], mac);
98 bin_clear_free(buf, len[i]);
103 pad_block(tmp2, addr[i], len[i]);
106 return omac1_aes_128(key, tmp, sizeof(tmp), mac);
110 int aes_siv_encrypt(const u8 *key, const u8 *pw,
111 size_t pwlen, size_t num_elem,
112 const u8 *addr[], const size_t *len, u8 *out)
116 const u8 *k1 = key, *k2 = key + 16;
117 u8 v[AES_BLOCK_SIZE];
121 if (num_elem > ARRAY_SIZE(_addr) - 1)
124 for (i = 0; i < num_elem; i++) {
128 _addr[num_elem] = pw;
129 _len[num_elem] = pwlen;
131 if (aes_s2v(k1, num_elem + 1, _addr, _len, v))
135 crypt_pw = out + AES_BLOCK_SIZE;
137 os_memcpy(iv, v, AES_BLOCK_SIZE);
138 os_memcpy(crypt_pw, pw, pwlen);
140 /* zero out 63rd and 31st bits of ctr (from right) */
143 return aes_128_ctr_encrypt(k2, v, crypt_pw, pwlen);
147 int aes_siv_decrypt(const u8 *key, const u8 *iv_crypt, size_t iv_c_len,
148 size_t num_elem, const u8 *addr[], const size_t *len,
153 const u8 *k1 = key, *k2 = key + 16;
157 u8 iv[AES_BLOCK_SIZE];
158 u8 check[AES_BLOCK_SIZE];
160 if (iv_c_len < AES_BLOCK_SIZE || num_elem > ARRAY_SIZE(_addr) - 1)
162 crypt_len = iv_c_len - AES_BLOCK_SIZE;
164 for (i = 0; i < num_elem; i++) {
168 _addr[num_elem] = out;
169 _len[num_elem] = crypt_len;
171 os_memcpy(iv, iv_crypt, AES_BLOCK_SIZE);
172 os_memcpy(out, iv_crypt + AES_BLOCK_SIZE, crypt_len);
177 ret = aes_128_ctr_encrypt(k2, iv, out, crypt_len);
181 ret = aes_s2v(k1, num_elem + 1, _addr, _len, check);
184 if (os_memcmp(check, iv_crypt, AES_BLOCK_SIZE) == 0)