Embedded systems coursework 2.
Fork of Crypto_light by
Diff: MD5.cpp
- Revision:
- 1:14a7cea431aa
- Parent:
- 0:7a1237bd2d13
- Child:
- 3:85c6ee25cf3e
diff -r 7a1237bd2d13 -r 14a7cea431aa MD5.cpp --- a/MD5.cpp Sat Sep 07 23:47:28 2013 +0000 +++ b/MD5.cpp Mon Sep 09 12:15:26 2013 +0000 @@ -97,24 +97,11 @@ } int offset = 64-bufferLength; memcpy(&buffer[bufferLength], in, offset); - uint32_t tmpA = a, tmpB = b, tmpC = c, tmpD = d; computeRounds(&a, &b, &c, &d, buffer); - a += tmpA; - b += tmpB; - c += tmpC; - d += tmpD; while(length-offset > 64) { memcpy(buffer, &in[offset], 64); - tmpA = a; - tmpB = b; - tmpC = c; - tmpD = d; computeRounds(&a, &b, &c, &d, buffer); - a += tmpA; - b += tmpB; - c += tmpC; - d += tmpD; offset += 64; } if(offset > length) @@ -158,7 +145,10 @@ void MD5::computeRounds(uint32_t *a2, uint32_t *b2, uint32_t *c2, uint32_t *d2, uint8_t *buffer) { + uint32_t a = *a2, b = *b2, c = *c2, d = *d2; + uint32_t tmpA = a, tmpB = b, tmpC = c, tmpD = d; + uint32_t x[16]; for(int j = 0; j < 16; ++j) memcpy(&x[j], &buffer[j*4], 4); @@ -187,6 +177,11 @@ ROUND4(a,b,c,d,8,6,57); ROUND4(d,a,b,c,15,10,58); ROUND4(c,d,a,b,6,15,59); ROUND4(b,c,d,a,13,21,60); ROUND4(a,b,c,d,4,6,61); ROUND4(d,a,b,c,11,10,62); ROUND4(c,d,a,b,2,15,63); ROUND4(b,c,d,a,9,21,64); + a += tmpA; + b += tmpB; + c += tmpC; + d += tmpD; + *a2 = a; *b2 = b; *c2 = c; @@ -200,30 +195,38 @@ padding = 56 - (length % 64); else padding = 56 + (64 - (length % 64)); - uint32_t totalLength = length + padding + 8; - uint8_t *buffer = new uint8_t[totalLength]; - memcpy(buffer, msg, length); - buffer[length] = 0x80; - memset(&buffer[length+1], 0, padding-1); + + uint32_t a = A, b = B, c = C, d = D; + + uint32_t offset = 0; + while(length - offset >= 64) + { + computeRounds(&a, &b, &c, &d, &msg[offset]); + offset += 64; + } + uint8_t buffer[64]; + memcpy(buffer, &msg[offset], length-offset); + uint8_t bufferLength = length - offset; + buffer[bufferLength++] = 0x80; + padding--; + while(padding > 0) + { + if(bufferLength == 64) + { + computeRounds(&a, &b, &c, &d, buffer); + bufferLength = 0; + } + buffer[bufferLength++] = 0; + padding--; + } uint64_t lengthBit = length * 8; uint32_t lengthBitLow = lengthBit; uint32_t lengthBitHigh = lengthBit >> 32; - memcpy(&buffer[length+padding], &lengthBitLow, 4); - memcpy(&buffer[length+padding+4], &lengthBitHigh, 4); + memcpy(&buffer[56], &lengthBitLow, 4); + memcpy(&buffer[60], &lengthBitHigh, 4); - uint32_t a = A, b = B, c = C, d = D; - for(int i = 0; i < totalLength/64; ++i) - { - uint32_t tmpA = a, tmpB = b, tmpC = c, tmpD = d; - computeRounds(&a, &b, &c, &d, &buffer[64*i]); - - a += tmpA; - b += tmpB; - c += tmpC; - d += tmpD; - } - delete[] buffer; - + computeRounds(&a, &b, &c, &d, buffer); + memcpy(digest, &a, 4); memcpy(&digest[4], &b, 4); memcpy(&digest[8], &c, 4);