Cryptography .NET, Avoiding Timing Attack

前端 未结 2 1584
面向向阳花
面向向阳花 2020-12-31 05:04

I was browsing crackstation.net website and came across this code which was commented as following:

Compares two byte arrays in length-constant time.

2条回答
  •  长情又很酷
    2020-12-31 05:41

    this version goes on for the length of the input 'a'

        private static bool SlowEquals(byte[] a, byte[] b)
        {
            uint diff = (uint)a.Length ^ (uint)b.Length;
            byte[] c = new byte[] { 0 };
            for (int i = 0; i < a.Length; i++)
                diff |= (uint)(GetElem(a, i, c, 0) ^ GetElem(b, i, c, 0));
            return diff == 0;
        }
    
        private static byte GetElem(byte[] x, int i, byte[] c, int i0)
        {
            bool ok = (i < x.Length);
            return (ok ? x : c)[ok ? i : i0];
        }
    

提交回复
热议问题