]> www.wagner.pp.ru Git - openssl-gost/engine.git/blobdiff - gosthash2012.c
gosthash2012: Simpler version of add512
[openssl-gost/engine.git] / gosthash2012.c
index dce3e9b38e464111d534aa5c8b0d7c0a1d69d98a..3dacc3531955e6f12c43b59ea7277cb27518ea1b 100644 (file)
@@ -35,58 +35,52 @@ void init_gost2012_hash_ctx(gost2012_hash_ctx * CTX,
     memset(CTX, 0, sizeof(gost2012_hash_ctx));
 
     CTX->digest_size = digest_size;
+    /*
+     * IV for 512-bit hash should be 0^512
+     * IV for 256-bit hash should be (00000001)^64
+     *
+     * It's already zeroed when CTX is cleared above, so we only
+     * need to set it to 0x01-s for 256-bit hash.
+     */
     if (digest_size == 256)
         memset(&CTX->h, 0x01, sizeof(uint512_u));
-    else
-        memset(&CTX->h, 0x00, sizeof(uint512_u));
 }
 
 static INLINE void pad(gost2012_hash_ctx * CTX)
 {
-    unsigned char buf[64];
-
-    if (CTX->bufsize > 63)
-        return;
+    memset(&(CTX->buffer[CTX->bufsize]), 0, sizeof(CTX->buffer) - CTX->bufsize);
+    CTX->buffer[CTX->bufsize] = 1;
 
-    memset(&buf, 0x00, sizeof buf);
-    memcpy(&buf, CTX->buffer, CTX->bufsize);
-
-    buf[CTX->bufsize] = 0x01;
-    memcpy(CTX->buffer, &buf, sizeof buf);
 }
 
 static INLINE void add512(const union uint512_u *x,
                           const union uint512_u *y, union uint512_u *r)
 {
 #ifndef __GOST3411_BIG_ENDIAN__
-    unsigned int CF, OF;
-    unsigned long long tmp;
+    unsigned int CF;
     unsigned int i;
 
     CF = 0;
-    for (i = 0; i < 8; i++)
-    {
-        /* Detecting integer overflow condition for three numbers
-         * in a portable way is tricky a little. */
-
-        /* Step 1: numbers cause overflow */
-        tmp = x->QWORD[i] + y->QWORD[i];
-
-        /* Compare with any of two summands, no need to check both */
-        if (tmp < x->QWORD[i])
-            OF = 1;
-        else
-            OF = 0;
-
-        /* Step 2: carry bit causes overflow */
-        tmp += CF;
-
-        if (CF > 0 && tmp == 0)
-            OF = 1;
-
-        CF = OF;
-
-        r->QWORD[i] = tmp;
+    for (i = 0; i < 8; i++) {
+       const unsigned long long left = x->QWORD[i];
+       unsigned long long sum;
+
+       sum = left + y->QWORD[i] + CF;
+       /*
+        * (sum == left): is noop, because it's possible only
+        * when `left' is added with `0 + 0' or with `ULLONG_MAX + 1',
+        * in that case `CF' (carry) retain previous value, which is correct,
+        * because when `left + 0 + 0' there was no overflow (thus no carry),
+        * and when `left + ULLONG_MAX + 1' value is wrapped back to
+        * itself with overflow, thus creating carry.
+        *
+        * (sum != left):
+        * if `sum' is not wrapped (sum > left) there should not be carry,
+        * if `sum' is wrapped (sum < left) there should be carry.
+        */
+       if (sum != left)
+           CF = (sum < left);
+       r->QWORD[i] = sum;
     }
 #else
     const unsigned char *xp, *yp;