From 2cab25bf140eff04aef44b87e5a2ac791cc74c30 Mon Sep 17 00:00:00 2001 From: Simon Tatham Date: Thu, 18 May 2017 18:49:35 +0100 Subject: General MD5 cleanups. I did these in passing while looking for the bug in the previous commit, and they seem like general improvements, so I'll keep them. --- md5.c | 58 ++++++++++++++++++++++++---------------------------------- 1 file changed, 24 insertions(+), 34 deletions(-) diff --git a/md5.c b/md5.c index 2fbbeec..648620c 100644 --- a/md5.c +++ b/md5.c @@ -153,7 +153,6 @@ static void MD5Init(struct MD5Context *s) static void MD5Update(struct MD5Context *s, unsigned char const *p, unsigned len) { - unsigned char *q = (unsigned char *) p; uint32_t wordblock[16]; int i; @@ -162,33 +161,31 @@ static void MD5Update(struct MD5Context *s, unsigned char const *p, */ s->len += len; - if (s->blkused + len < BLKSIZE) { + while (len >= BLKSIZE - s->blkused) { + /* + * Complete and process a hash block. + */ + memcpy(s->block + s->blkused, p, BLKSIZE - s->blkused); + p += BLKSIZE - s->blkused; + len -= BLKSIZE - s->blkused; + /* Now process the block. Gather bytes little-endian into words */ + for (i = 0; i < 16; i++) { + wordblock[i] = + (((uint32_t) s->block[i * 4 + 3]) << 24) | + (((uint32_t) s->block[i * 4 + 2]) << 16) | + (((uint32_t) s->block[i * 4 + 1]) << 8) | + (((uint32_t) s->block[i * 4 + 0]) << 0); + } + MD5_Block(&s->core, wordblock); + s->blkused = 0; + } + + if (len > 0) { /* - * Trivial case: just add to the block. + * Append to the block. */ - memcpy(s->block + s->blkused, q, len); + memcpy(s->block + s->blkused, p, len); s->blkused += len; - } else { - /* - * We must complete and process at least one block. - */ - while (s->blkused + len >= BLKSIZE) { - memcpy(s->block + s->blkused, q, BLKSIZE - s->blkused); - q += BLKSIZE - s->blkused; - len -= BLKSIZE - s->blkused; - /* Now process the block. Gather bytes little-endian into words */ - for (i = 0; i < 16; i++) { - wordblock[i] = - (((uint32_t) s->block[i * 4 + 3]) << 24) | - (((uint32_t) s->block[i * 4 + 2]) << 16) | - (((uint32_t) s->block[i * 4 + 1]) << 8) | - (((uint32_t) s->block[i * 4 + 0]) << 0); - } - MD5_Block(&s->core, wordblock); - s->blkused = 0; - } - memcpy(s->block, q, len); - s->blkused = len; } } @@ -210,15 +207,8 @@ static void MD5Final(uint32_t output[4], struct MD5Context *s) c[0] = 0x80; MD5Update(s, c, pad); - c[7] = (len >> (8*7)) & 0xFF; - c[6] = (len >> (8*6)) & 0xFF; - c[5] = (len >> (8*5)) & 0xFF; - c[4] = (len >> (8*4)) & 0xFF; - c[3] = (len >> (8*3)) & 0xFF; - c[2] = (len >> (8*2)) & 0xFF; - c[1] = (len >> (8*1)) & 0xFF; - c[0] = (len >> (8*0)) & 0xFF; - + for (i = 0; i < 8; i++) + c[i] = (len >> (8*i)) & 0xFF; MD5Update(s, c, 8); for (i = 0; i < 4; i++) -- cgit v1.2.3-55-g6feb