ArduinoLibs
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
AES128.cpp
1 /*
2  * Copyright (C) 2015 Southern Storm Software, Pty Ltd.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20  * DEALINGS IN THE SOFTWARE.
21  */
22 
23 #include "AES.h"
24 #include "Crypto.h"
25 #include <string.h>
26 
41 {
42  rounds = 10;
43  schedule = sched;
44 }
45 
46 AES128::~AES128()
47 {
48  clean(sched);
49 }
50 
55 size_t AES128::keySize() const
56 {
57  return 16;
58 }
59 
60 bool AES128::setKey(const uint8_t *key, size_t len)
61 {
62  if (len != 16)
63  return false;
64 
65  // Copy the key itself into the first 16 bytes of the schedule.
66  uint8_t *schedule = sched;
67  memcpy(schedule, key, 16);
68 
69  // Expand the key schedule until we have 176 bytes of expanded key.
70  uint8_t iteration = 1;
71  uint8_t n = 16;
72  uint8_t w = 4;
73  while (n < 176) {
74  if (w == 4) {
75  // Every 16 bytes (4 words) we need to apply the key schedule core.
76  keyScheduleCore(schedule + 16, schedule + 12, iteration);
77  schedule[16] ^= schedule[0];
78  schedule[17] ^= schedule[1];
79  schedule[18] ^= schedule[2];
80  schedule[19] ^= schedule[3];
81  ++iteration;
82  w = 0;
83  } else {
84  // Otherwise just XOR the word with the one 16 bytes previous.
85  schedule[16] = schedule[12] ^ schedule[0];
86  schedule[17] = schedule[13] ^ schedule[1];
87  schedule[18] = schedule[14] ^ schedule[2];
88  schedule[19] = schedule[15] ^ schedule[3];
89  }
90 
91  // Advance to the next word in the schedule.
92  schedule += 4;
93  n += 4;
94  ++w;
95  }
96 
97  return true;
98 }
size_t keySize() const
Size of a 128-bit AES key in bytes.
Definition: AES128.cpp:55
bool setKey(const uint8_t *key, size_t len)
Sets the key to use for future encryption and decryption operations.
Definition: AES128.cpp:60
AES128()
Constructs an AES 128-bit block cipher with no initial key.
Definition: AES128.cpp:40