3 This file is part of the Crypto-avr-lib/microcrypt-lib.
4 Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de)
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * a bitsliced implementation of the serpent cipher for avr microcontrollers
22 * email: daniel.otte@rub.de
27 #include <string.h> /* memset() */
28 #include <avr/pgmspace.h>
30 #include "serpent-sboxes.h"
32 /******************************************************************************/
34 void memxor(void * dest, void * src, uint8_t size){
36 *((uint8_t*)dest) ^= *((uint8_t*)src);
37 dest = (uint8_t*)dest +1;
38 src = (uint8_t*)src +1;
42 /******************************************************************************/
44 uint32_t rotl32(uint32_t a, uint8_t n){
45 return ((a<<n) | (a>>(32-n)));
49 uint32_t rotr32(uint32_t a, uint8_t n){
50 return ((a>>n) | (a<<(32-n)));
54 #define X0 (((uint32_t*)b)[0])
55 #define X1 (((uint32_t*)b)[1])
56 #define X2 (((uint32_t*)b)[2])
57 #define X3 (((uint32_t*)b)[3])
59 static void lt(uint8_t *b){
72 static void inv_lt(uint8_t *b){
85 #define GOLDEN_RATIO 0x9e3779b9l
87 static uint32_t gen_w(uint32_t * b, uint8_t i){
89 ret = b[0] ^ b[3] ^ b[5] ^ b[7] ^ GOLDEN_RATIO ^ (uint32_t)i;
90 ret = rotl32(ret, 11);
94 /* key must be 256bit (32 byte) large! */
95 void serpent_init(void * key, uint8_t keysize, serpent_ctx_t * ctx){
99 /* keysize is less than 256 bit, padding needed */
100 memset(buffer, 0, 32);
101 memcpy(buffer, key, (keysize+7)/8);
102 ((uint8_t*)buffer)[keysize/8] |= 1<<(keysize%8);
104 /* keysize is 256 bit */
105 memcpy(buffer, key, 32);
109 ctx->k[i][j] = gen_w(buffer, i*4+j);
110 memmove(buffer, &(buffer[1]), 7*4); /* shift buffer one to the "left" */
111 buffer[7] = ctx->k[i][j];
115 sbox128(ctx->k[i],3-i);
120 void serpent_enc(void* buffer, serpent_ctx_t * ctx){
123 memxor((uint8_t*)buffer, ctx->k[i], 16);
125 lt((uint8_t*)buffer);
127 memxor((uint8_t*)buffer, ctx->k[i], 16);
130 memxor((uint8_t*)buffer, ctx->k[i], 16);
133 void serpent_dec(void* buffer, serpent_ctx_t * ctx){
136 memxor((uint8_t*)buffer, ctx->k[i], 16);
138 inv_sbox128(buffer, i);
139 memxor((uint8_t*)buffer, ctx->k[i], 16);
142 inv_lt((uint8_t*)buffer);
143 inv_sbox128(buffer, i);
144 memxor((uint8_t*)buffer, ctx->k[i], 16);