]> git.cryptolib.org Git - avr-crypto-lib.git/blob - rc5.c
5bfaaf3159e4959a9afc599faaf63b876662f0bb
[avr-crypto-lib.git] / rc5.c
1 /* rc5.c a C implementation of RC5 for AVR microcontrollers
2  * 
3  * author: Daniel Otte 
4  * email:  daniel.otte@rub.de
5  * license: GPLv3
6  * 
7  * this implementation is limited to 64bit blocks and a maximum of 255 rounds
8  * 
9  */
10
11 #include <stdint.h>
12 #include <stdlib.h> /* malloc() & free() */
13 #include <string.h> /* memset() & memcpy() */
14 #include "rc5.h" 
15  
16
17 #define A (((uint32_t*)buffer)[0])
18 #define B (((uint32_t*)buffer)[1])
19 #define ROTL32(v,n) (((v)<<(n))|((v)>>(32-(n))))
20 #define ROTR32(v,n) (((v)>>(n))|((v)<<(32-(n))))
21
22 void rc5_enc(void* buffer, const rc5_ctx_t* ctx){
23         uint8_t i;
24         A += ctx->s[0];
25         B += ctx->s[1];
26         for(i=0; i<ctx->rounds; ++i){
27                 A = ROTL32(A^B, B&31) + ctx->s[(i+1)*2+0];
28                 B = ROTL32(A^B, A&31) + ctx->s[(i+1)*2+1];
29         } 
30 }
31
32 void rc5_dec(void* buffer, const rc5_ctx_t* ctx){
33         uint8_t i;
34         for(i=ctx->rounds; i>0; --i){
35                 B = ROTR32(B - ctx->s[i*2+1], A&31) ^ A;
36                 A = ROTR32(A - ctx->s[i*2+0], B&31) ^ B;
37         } 
38         B -= ctx->s[1];
39         A -= ctx->s[0];
40 }
41 /*
42 P32 = 10110111111000010101000101100011 = b7e15163
43 Q32 = 10011110001101110111100110111001 = 9e3779b9
44 */
45 #define P32 0xb7e15163
46 #define Q32 0x9e3779b9
47
48
49 void rc5_init(void* key, uint16_t keysize_b, uint8_t rounds, rc5_ctx_t* ctx){
50         uint16_t c,n,m,j,i,t;
51         uint32_t a,b,l[(keysize_b+31)/32];
52         ctx->rounds = rounds;
53         t=2*(rounds+1);
54         c=(keysize_b+31)/32;
55         ctx->s = malloc(t*sizeof(uint32_t));
56         
57         memset(l, 0, sizeof(uint32_t)*c);
58         memcpy(l, key, (keysize_b+7)/8);
59         
60         ctx->s[0] = P32;
61         for(i=1; i<t; ++i){
62                 ctx->s[i] = ctx->s[i-1] + Q32;
63         }
64         
65         m = ((t>c)?t:c)*3;
66         i=j=0;
67         a=b=0;
68         for(n=0; n<m; ++n){
69                 a=ctx->s[i]=ROTL32(ctx->s[i]+a+b, 3);
70                 b=l[j]=ROTL32(l[j]+a+b, (a+b)&31);
71                 i=(i+1)%t;
72                 j=(j+1)%c;
73         }
74 }
75
76 void rc5_free(rc5_ctx_t* ctx){
77         if(ctx->s)
78                 free(ctx->s);
79 }
80