Revert "Merge branch 'upstream' into tizen"
[platform/upstream/nettle.git] / aes-set-encrypt-key.c
1 /* aes-set-encrypt-key.c
2  *
3  * Key setup for the aes/rijndael block cipher.
4  */
5
6 /* nettle, low-level cryptographics library
7  *
8  * Copyright (C) 2000, 2001, 2002 Rafael R. Sevilla, Niels Möller
9  *  
10  * The nettle library is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or (at your
13  * option) any later version.
14  * 
15  * The nettle library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18  * License for more details.
19  * 
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with the nettle library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23  * MA 02111-1301, USA.
24  */
25
26 /* Originally written by Rafael R. Sevilla <dido@pacific.net.ph> */
27
28 #if HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <assert.h>
33
34 #include "aes-internal.h"
35 #include "macros.h"
36
37 void
38 aes_set_encrypt_key(struct aes_ctx *ctx,
39                     unsigned keysize, const uint8_t *key)
40 {
41   static const uint8_t rcon[10] = {
42     0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36,
43   };
44   unsigned nk, nr, i, lastkey;
45   uint32_t temp;
46   const uint8_t *rp;
47
48   assert(keysize >= AES_MIN_KEY_SIZE);
49   assert(keysize <= AES_MAX_KEY_SIZE);
50   
51   /* Truncate keysizes to the valid key sizes provided by Rijndael */
52   if (keysize == 32) {
53     nk = 8;
54     nr = 14;
55   } else if (keysize >= 24) {
56     nk = 6;
57     nr = 12;
58   } else { /* must be 16 or more */
59     nk = 4;
60     nr = 10;
61   }
62
63   lastkey = (AES_BLOCK_SIZE/4) * (nr + 1);
64   ctx->nrounds = nr;
65
66   for (i=0, rp = rcon; i<nk; i++)
67     ctx->keys[i] = LE_READ_UINT32(key + i*4);
68
69   for (i=nk; i<lastkey; i++)
70     {
71       temp = ctx->keys[i-1];
72       if (i % nk == 0)
73         temp = SUBBYTE(ROTL32(24, temp), aes_sbox) ^ *rp++;
74
75       else if (nk > 6 && (i%nk) == 4)
76         temp = SUBBYTE(temp, aes_sbox);
77
78       ctx->keys[i] = ctx->keys[i-nk] ^ temp;
79     }
80 }
81