]> www.wagner.pp.ru Git - openssl-gost/engine.git/blobdiff - gosthash2012.c
gosthash2012: Remove redundant `hash' field from `struct gost2012_hash_ctx'
[openssl-gost/engine.git] / gosthash2012.c
index 6a89237e1d9ba7ba35f0924780cd0c147385df22..dce3e9b38e464111d534aa5c8b0d7c0a1d69d98a 100644 (file)
@@ -32,8 +32,6 @@
 void init_gost2012_hash_ctx(gost2012_hash_ctx * CTX,
                             const unsigned int digest_size)
 {
-    unsigned int i;
-
     memset(CTX, 0, sizeof(gost2012_hash_ctx));
 
     CTX->digest_size = digest_size;
@@ -62,18 +60,33 @@ static INLINE void add512(const union uint512_u *x,
 {
 #ifndef __GOST3411_BIG_ENDIAN__
     unsigned int CF, OF;
+    unsigned long long tmp;
     unsigned int i;
 
     CF = 0;
-    for (i = 0; i < 8; i++) {
-        r->QWORD[i] = x->QWORD[i] + y->QWORD[i];
-        if (r->QWORD[i] < y->QWORD[i] || r->QWORD[i] < x->QWORD[i])
+    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;
 
-        r->QWORD[i] += CF;
+        /* Step 2: carry bit causes overflow */
+        tmp += CF;
+
+        if (CF > 0 && tmp == 0)
+            OF = 1;
+
         CF = OF;
+
+        r->QWORD[i] = tmp;
     }
 #else
     const unsigned char *xp, *yp;
@@ -144,10 +157,13 @@ static void g(union uint512_u *h, const union uint512_u *N,
 
 static INLINE void stage2(gost2012_hash_ctx * CTX, const unsigned char *data)
 {
-    g(&(CTX->h), &(CTX->N), data);
+    union uint512_u m;
+
+    memcpy(&m, data, sizeof(m));
+    g(&(CTX->h), &(CTX->N), (const unsigned char *)&m);
 
     add512(&(CTX->N), &buffer512, &(CTX->N));
-    add512(&(CTX->Sigma), (const union uint512_u *)data, &(CTX->Sigma));
+    add512(&(CTX->Sigma), &m, &(CTX->Sigma));
 }
 
 static INLINE void stage3(gost2012_hash_ctx * CTX)
@@ -176,7 +192,6 @@ static INLINE void stage3(gost2012_hash_ctx * CTX)
     g(&(CTX->h), &buffer0, (const unsigned char *)&(CTX->N));
 
     g(&(CTX->h), &buffer0, (const unsigned char *)&(CTX->Sigma));
-    memcpy(&(CTX->hash), &(CTX->h), sizeof(uint512_u));
 }
 
 /*
@@ -226,7 +241,7 @@ void gost2012_finish_hash(gost2012_hash_ctx * CTX, unsigned char *digest)
     CTX->bufsize = 0;
 
     if (CTX->digest_size == 256)
-        memcpy(digest, &(CTX->hash.QWORD[4]), 32);
+        memcpy(digest, &(CTX->h.QWORD[4]), 32);
     else
-        memcpy(digest, &(CTX->hash.QWORD[0]), 64);
+        memcpy(digest, &(CTX->h.QWORD[0]), 64);
 }