From 9ed077d752daa0f7407c42ce0e01d2ef3d87d3da Mon Sep 17 00:00:00 2001 From: Helder Eijs Date: Sat, 24 Feb 2018 16:53:48 +0100 Subject: [PATCH] Clean up SHA1 code --- lib/Crypto/Hash/SHA1.py | 4 +++- src/SHA1.c | 35 ++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/lib/Crypto/Hash/SHA1.py b/lib/Crypto/Hash/SHA1.py index 06f2fe7c..3cc924e4 100644 --- a/lib/Crypto/Hash/SHA1.py +++ b/lib/Crypto/Hash/SHA1.py @@ -28,13 +28,15 @@ from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, _raw_sha1_lib = load_pycryptodome_raw_lib("Crypto.Hash._SHA1", """ + #define SHA1_DIGEST_SIZE 20 + int SHA1_init(void **shaState); int SHA1_destroy(void *shaState); int SHA1_update(void *hs, const uint8_t *buf, size_t len); int SHA1_digest(const void *shaState, - uint8_t digest[16]); + uint8_t digest[SHA1_DIGEST_SIZE]); int SHA1_copy(const void *src, void *dst); """) diff --git a/src/SHA1.c b/src/SHA1.c index ba16084a..509b5ed8 100644 --- a/src/SHA1.c +++ b/src/SHA1.c @@ -105,6 +105,25 @@ FAKE_INIT(SHA1) #define MIN(a,b) (a> 8); + p[1] = (uint8_t)(number >> 16); + p[0] = (uint8_t)(number >> 24); +} + typedef struct t_hash_state { uint32_t h[5]; uint8_t buf[BLOCK_SIZE]; /** 64 bytes == 512 bits == sixteen 32-bit words **/ @@ -124,13 +143,10 @@ static void sha_compress(hash_state * hs) uint32_t a, b, c, d, e; uint32_t W[16]; int i; - uint8_t *p; /** Words flow in in big-endian mode **/ - p = &hs->buf[0]; for (i=0; i<16; i++) { - W[i] = ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | (uint32_t)p[3]; - p += 4; + W[i] = get_be_32(&hs->buf[i*4]); } a = hs->h[0]; @@ -318,19 +334,16 @@ static int sha_finalize(hash_state *hs, uint8_t *hash /** [DIGEST_SIZE] **/) **/ left = BLOCK_SIZE - hs->curlen; memset(&hs->buf[hs->curlen], 0, left); - for (i=7; i>=0; i--) { - hs->buf[BLOCK_SIZE-i-1] = 0xFF & (hs->totbits >> (i*8)); - } + put_be_32((uint32_t)(hs->totbits >> 32), &hs->buf[BLOCK_SIZE-8]); + put_be_32((uint32_t)hs->totbits, &hs->buf[BLOCK_SIZE-4]); /** compress one last time **/ sha_compress(hs); /** create final hash **/ for (i=0; i<5; i++) { - *hash++ = hs->h[i] >> 24; - *hash++ = hs->h[i] >> 16; - *hash++ = hs->h[i] >> 8; - *hash++ = hs->h[i]; + put_be_32(hs->h[i], hash); + hash += 4; } return 0;