summary refs log tree commit diff
path: root/crypto/src
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2013-07-10 15:09:29 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2013-07-10 15:09:29 +0700
commitb2e8e34a92f1fedfd4ac96d77c6bf3a120835e23 (patch)
tree4e16024442cfac7f7d8f64f40c3bfdc7fd8e77e0 /crypto/src
parentGuard against passing IV thru CMac (diff)
downloadBouncyCastle.NET-ed25519-b2e8e34a92f1fedfd4ac96d77c6bf3a120835e23.tar.xz
Attempt to perform doubling operation in constant time
Diffstat (limited to 'crypto/src')
-rw-r--r--crypto/src/crypto/macs/CMac.cs36
1 files changed, 23 insertions, 13 deletions
diff --git a/crypto/src/crypto/macs/CMac.cs b/crypto/src/crypto/macs/CMac.cs
index 997145a4d..b55a05605 100644
--- a/crypto/src/crypto/macs/CMac.cs
+++ b/crypto/src/crypto/macs/CMac.cs
@@ -105,20 +105,30 @@ namespace Org.BouncyCastle.Crypto.Macs
             get { return cipher.AlgorithmName; }
         }
 
-        private static byte[] doubleLu(
-            byte[] inBytes)
+        private static int ShiftLeft(byte[] block, byte[] output)
         {
-            int FirstBit = (inBytes[0] & 0xFF) >> 7;
-            byte[] ret = new byte[inBytes.Length];
-            for (int i = 0; i < inBytes.Length - 1; i++)
+            int i = 16;
+            uint bit = 0;
+            while (--i >= 0)
             {
-                ret[i] = (byte)((inBytes[i] << 1) + ((inBytes[i + 1] & 0xFF) >> 7));
-            }
-            ret[inBytes.Length - 1] = (byte)(inBytes[inBytes.Length - 1] << 1);
-            if (FirstBit == 1)
-            {
-                ret[inBytes.Length - 1] ^= inBytes.Length == 16 ? CONSTANT_128 : CONSTANT_64;
+                uint b = block[i];
+                output[i] = (byte)((b << 1) | bit);
+                bit = (b >> 7) & 1;
             }
+            return (int)bit;
+        }
+
+        private static byte[] DoubleLu(byte[] input)
+        {
+            byte[] ret = new byte[input.Length];
+            int carry = ShiftLeft(input, ret);
+            int xor = input.Length == 16 ? CONSTANT_128 : CONSTANT_64;
+
+            /*
+             * NOTE: This construction is an attempt at a constant-time implementation.
+             */
+            ret[input.Length - 1] ^= (byte)(xor >> ((1 - carry) << 3));
+
             return ret;
         }
 
@@ -132,8 +142,8 @@ namespace Org.BouncyCastle.Crypto.Macs
                 //initializes the L, Lu, Lu2 numbers
                 L = new byte[ZEROES.Length];
                 cipher.ProcessBlock(ZEROES, 0, L, 0);
-                Lu = doubleLu(L);
-                Lu2 = doubleLu(Lu);
+                Lu = DoubleLu(L);
+                Lu2 = DoubleLu(Lu);
             }
             else if (parameters != null)
             {