1
2
3
4
5
6
7#include <common.h>
8#include <linux/errno.h>
9#include "crypto.h"
10#include "uboot_aes.h"
11
12static u8 zero_key[16];
13
14#define AES_CMAC_CONST_RB 0x87
15
16enum security_op {
17 SECURITY_SIGN = 1 << 0,
18 SECURITY_ENCRYPT = 1 << 1,
19};
20
21
22
23
24
25
26
27
28static void left_shift_vector(u8 *in, u8 *out, int size)
29{
30 int carry = 0;
31 int i;
32
33 for (i = size - 1; i >= 0; i--) {
34 out[i] = (in[i] << 1) | carry;
35 carry = in[i] >> 7;
36 }
37}
38
39
40
41
42
43
44
45
46
47
48static void sign_object(u8 *key, u8 *key_schedule, u8 *src, u8 *dst,
49 u32 num_aes_blocks)
50{
51 u8 tmp_data[AES_KEY_LENGTH];
52 u8 iv[AES_KEY_LENGTH] = {0};
53 u8 left[AES_KEY_LENGTH];
54 u8 k1[AES_KEY_LENGTH];
55 u8 *cbc_chain_data;
56 unsigned i;
57
58 cbc_chain_data = zero_key;
59
60
61 for (i = 0; i < AES_KEY_LENGTH; i++)
62 tmp_data[i] = 0;
63
64 aes_cbc_encrypt_blocks(key_schedule, iv, tmp_data, left, 1);
65
66 left_shift_vector(left, k1, sizeof(left));
67
68 if ((left[0] >> 7) != 0)
69 k1[AES_KEY_LENGTH-1] ^= AES_CMAC_CONST_RB;
70
71
72 for (i = 0; i < num_aes_blocks; i++) {
73
74 aes_apply_cbc_chain_data(cbc_chain_data, src, tmp_data);
75
76
77 if (i == num_aes_blocks - 1)
78 aes_apply_cbc_chain_data(tmp_data, k1, tmp_data);
79
80
81 aes_encrypt(tmp_data, key_schedule, dst);
82
83 debug("sign_obj: block %d of %d\n", i, num_aes_blocks);
84
85
86 cbc_chain_data = dst;
87 src += AES_KEY_LENGTH;
88 }
89}
90
91
92
93
94
95
96
97
98
99
100static int encrypt_and_sign(u8 *key, enum security_op oper, u8 *src,
101 u32 length, u8 *sig_dst)
102{
103 u32 num_aes_blocks;
104 u8 key_schedule[AES_EXPAND_KEY_LENGTH];
105 u8 iv[AES_KEY_LENGTH] = {0};
106
107 debug("encrypt_and_sign: length = %d\n", length);
108
109
110
111
112
113 aes_expand_key(oper & SECURITY_ENCRYPT ? key : zero_key, key_schedule);
114
115 num_aes_blocks = (length + AES_KEY_LENGTH - 1) / AES_KEY_LENGTH;
116
117 if (oper & SECURITY_ENCRYPT) {
118
119 debug("encrypt_and_sign: begin encryption\n");
120 aes_cbc_encrypt_blocks(key_schedule, iv, src, src,
121 num_aes_blocks);
122 debug("encrypt_and_sign: end encryption\n");
123 }
124
125 if (oper & SECURITY_SIGN) {
126
127 debug("encrypt_and_sign: begin signing\n");
128 sign_object(key, key_schedule, src, sig_dst, num_aes_blocks);
129 debug("encrypt_and_sign: end signing\n");
130 }
131
132 return 0;
133}
134
135int sign_data_block(u8 *source, unsigned length, u8 *signature)
136{
137 return encrypt_and_sign(zero_key, SECURITY_SIGN, source,
138 length, signature);
139}
140