6 * Description: Implementation of the RC6 cipher algorithm.
7 * This implementation is restricted to 32-bit words and to keys up to 65535 bit in length (but this is
8 * quite easy to expand), but free in the choice of number of rounds (0 to 125).
10 * THIS ONLY WORKS FOR LITTEL ENDIAN!!!
18 #define P32 0xB7E15163 /* e -2 */
19 #define Q32 0x9E3779B9 /* Golden Ratio -1 */
21 uint32_t rotl32(uint32_t a, uint8_t n){
22 n &= 0x1f; /* higher rotates would not bring anything */
23 return ( (a<<n)| (a>>(32-n)) );
26 uint32_t rotr32(uint32_t a, uint8_t n){
27 n &= 0x1f; /* higher rotates would not bring anything */
28 return ( (a>>n)| (a<<(32-n)) );
31 uint8_t rc6_init(rc6_ctx_t *s,void* key, uint16_t keylength){
32 return rc6_initl(s, key, keylength, 20);
36 uint8_t rc6_initl(rc6_ctx_t *s,void* key, uint16_t keylength, uint8_t rounds){
42 if(!(s->S=malloc((2*rounds+4)*sizeof(uint32_t))))
54 ((uint8_t*)&l)[i] = ((uint8_t*)key)[(c-1)*4 + i];
56 l = ((uint32_t*)key)[c-1];
60 for(i=1; i<2*rounds+4; ++i){
61 s->S[i] = s->S[i-1] + Q32;
65 v = 3 * ((c > 2*rounds+4)?c:(2*rounds+4));
67 a = s->S[i] = rotl32(s->S[i] + a + b, 3);
69 b = l = rotl32(l+a+b, a+b);
71 b = ((uint32_t*)key)[j] = rotl32(((uint32_t*)key)[j]+a+b, a+b);
73 i = (i+1) % (2*rounds+4);
79 void rc6_free(rc6_ctx_t *s){
84 #define A (((uint32_t*)block)[0])
85 #define B (((uint32_t*)block)[1])
86 #define C (((uint32_t*)block)[2])
87 #define D (((uint32_t*)block)[3])
89 void rc6_enc(rc6_ctx_t *s, void* block){
91 uint32_t t,u,x; /* greetings to Linux? */
94 for (i=1; i<=s->rounds; ++i){
95 t = rotl32(B * (2*B+1), LG_W);
96 u = rotl32(D * (2*D+1), LG_W);
97 A = rotl32((A ^ t), u) + s->S[2*i];
98 C = rotl32((C ^ u), t) + s->S[2*i+1];
105 A += s->S[2*s->rounds+2];
106 C += s->S[2*s->rounds+3];
109 void rc6_dec(rc6_ctx_t *s, void* block)
112 uint32_t t,u,x; /* greetings to Linux? */
114 C -= s->S[2*s->rounds+3];
115 A -= s->S[2*s->rounds+2];
117 for (i=s->rounds; i>0; --i){
123 u = rotl32(D * (2*D+1), LG_W);
124 t = rotl32(B * (2*B+1), LG_W);
125 C = rotr32(C - s->S[2*i+1], t) ^ u;
126 A = rotr32(A - s->S[2*i+0], u) ^ t;