[Title] Add packaging/nettle.spec to build nettle on OBS system
[external/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., 59 Temple Place - Suite 330, Boston,
23  * MA 02111-1307, 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
36 static unsigned
37 xtime(unsigned x)
38 {
39   assert (x < 0x100);
40
41   x <<= 1;
42   if (x & 0x100)
43     x ^= 0x11b;
44
45   assert (x < 0x100);
46
47   return x;
48 }
49
50 void
51 aes_set_encrypt_key(struct aes_ctx *ctx,
52                     unsigned keysize, const uint8_t *key)
53 {
54   unsigned nk, nr, i, lastkey;
55   uint32_t temp, rcon;
56
57   assert(keysize >= AES_MIN_KEY_SIZE);
58   assert(keysize <= AES_MAX_KEY_SIZE);
59   
60   /* Truncate keysizes to the valid key sizes provided by Rijndael */
61   if (keysize == 32) {
62     nk = 8;
63     nr = 14;
64   } else if (keysize >= 24) {
65     nk = 6;
66     nr = 12;
67   } else { /* must be 16 or more */
68     nk = 4;
69     nr = 10;
70   }
71
72   lastkey = (AES_BLOCK_SIZE/4) * (nr + 1);
73   ctx->nrounds = nr;
74   rcon = 1;
75   for (i=0; i<nk; i++)
76     {
77       ctx->keys[i] = key[i*4] + (key[i*4+1]<<8) + (key[i*4+2]<<16) +
78         (key[i*4+3]<<24);
79     }
80
81   for (i=nk; i<lastkey; i++)
82     {
83       temp = ctx->keys[i-1];
84       if (i % nk == 0)
85         {
86           temp = SUBBYTE(ROTBYTE(temp), aes_sbox) ^ rcon;
87           rcon = (uint32_t)xtime((uint8_t)rcon&0xff);
88         }
89       else if (nk > 6 && (i%nk) == 4)
90         {
91           temp = SUBBYTE(temp, aes_sbox);
92         }
93       ctx->keys[i] = ctx->keys[i-nk] ^ temp;
94     }
95 }
96