7 * \brief Implementation of the MD5 hash algorithm as described in RFC 1321
19 void md5_init(md5_ctx_t *s){
27 uint32_t md5_F(uint32_t x, uint32_t y, uint32_t z){
28 return ((x&y)|((~x)&z));
31 uint32_t md5_G(uint32_t x, uint32_t y, uint32_t z){
32 return ((x&z)|((~z)&y));
35 uint32_t md5_H(uint32_t x, uint32_t y, uint32_t z){
39 uint32_t md5_I(uint32_t x, uint32_t y, uint32_t z){
40 return (y ^ (x | (~z)));
43 typedef uint32_t md5_func_t(uint32_t, uint32_t, uint32_t);
45 #define ROTL32(x,n) (((x)<<(n)) | ((x)>>(32-(n))))
47 void md5_core(uint32_t* a, uint8_t as, void* block, uint8_t k, uint8_t s, uint8_t i, uint8_t fi){
49 md5_func_t* funcs[]={md5_F, md5_G, md5_H, md5_I};
51 /* a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
53 char funcc[]={'*', '-', '+', '~'};
54 uart_putstr("\r\n DBG: md5_core [");
56 uart_hexdump(&as, 1); uart_putc(' ');
57 uart_hexdump(&k, 1); uart_putc(' ');
58 uart_hexdump(&s, 1); uart_putc(' ');
59 uart_hexdump(&i, 1); uart_putc(']');
61 t = a[as] + funcs[fi](a[(as+1)&3], a[(as+2)&3], a[(as+3)&3]) + ((uint32_t*)block)[k] + md5_T[i] ;
62 a[as]=a[(as+1)&3] + ROTL32(t, s);
65 void md5_nextBlock(md5_ctx_t *state, void* block){
68 /* this requires other mixed sboxes */
70 uart_putstr("\r\n DBG: md5_nextBlock: block:\r\n");
71 uart_hexdump(block, 16); uart_putstr("\r\n");
72 uart_hexdump(block+16, 16); uart_putstr("\r\n");
73 uart_hexdump(block+32, 16); uart_putstr("\r\n");
74 uart_hexdump(block+48, 16); uart_putstr("\r\n");
83 uint8_t s1t[]={7,12,17,22};
86 md5_core(a, 4-n, block, m*4+n, s1t[n],i++,0);
90 uint8_t s2t[]={5,9,14,20};
93 md5_core(a, 4-n, block, (1+m*4+n*5)&0xf, s2t[n],i++,1);
97 uint8_t s3t[]={4,11,16,23};
100 md5_core(a, 4-n, block, (5-m*4+n*3)&0xf, s3t[n],i++,2);
104 uint8_t s4t[]={6,10,15,21};
107 md5_core(a, 4-n, block, (0-m*4+n*7)&0xf, s4t[n],i++,3);
117 void md5_lastBlock(md5_ctx_t *state, void* block, uint16_t length){
120 while (length >= 512){
121 md5_nextBlock(state, block);
123 block = ((uint8_t*)block) + 512/8;
126 memcpy(b, block, length/8);
127 /* insert padding one */
131 t = ((uint8_t*)block)[l];
132 t |= (0x80>>(length%8));
137 /* insert length value */
138 if(l+sizeof(uint64_t) > 512/8){
139 md5_nextBlock(state, b);
143 *((uint64_t*)&b[64-sizeof(uint64_t)]) = (state->counter * 512) + length;
144 md5_nextBlock(state, b);