From 9f82aac8cecbe3c44ba5ae56862c0a69b0a1a779 Mon Sep 17 00:00:00 2001 From: Dmitry Podgorny Date: Sat, 25 Oct 2014 16:37:21 +0300 Subject: [PATCH] sha1: compile-time endianness check for some compilers Newer gcc and clang provide macro __BYTE_ORDER__. --- src/sha1.c | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/sha1.c b/src/sha1.c index 84a6b7e..9af4f04 100644 --- a/src/sha1.c +++ b/src/sha1.c @@ -124,11 +124,22 @@ void SHAPrintContext(SHA1_CTX *context, char *msg){ static uint32_t host_to_be(uint32_t i) { +#define le_to_be(i) ((rol((i),24) & 0xFF00FF00) | (rol((i),8) & 0x00FF00FF)) +#if defined(__BIG_ENDIAN__) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) + return i; +#elif defined(__LITTLE_ENDIAN__) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) + return le_to_be(i); +#else /* fallback to run-time check */ static const union { - unsigned u; + uint32_t u; unsigned char c; } check = {1}; - return check.c ? (rol(i,24)&0xFF00FF00)|(rol(i,8)&0x00FF00FF) : i; + return check.c ? le_to_be(i) : i; +#endif } /* Hash a single 512-bit block. This is the core of the algorithm. */