diff options
author | chai <215380520@qq.com> | 2023-10-12 22:09:49 +0800 |
---|---|---|
committer | chai <215380520@qq.com> | 2023-10-12 22:09:49 +0800 |
commit | 8d2a2cd5de40e2b94ef5007c32832ed9a063dc40 (patch) | |
tree | a63dfbe815855925c9fb8f2804bd6ccfeffbd2eb /Tools/Hazel-Networking/Hazel/Crypto/Const.cs | |
parent | dd0c5d50e377d9be1e728463670908a6c9d2c14f (diff) |
+hazel-networking
Diffstat (limited to 'Tools/Hazel-Networking/Hazel/Crypto/Const.cs')
-rw-r--r-- | Tools/Hazel-Networking/Hazel/Crypto/Const.cs | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/Tools/Hazel-Networking/Hazel/Crypto/Const.cs b/Tools/Hazel-Networking/Hazel/Crypto/Const.cs new file mode 100644 index 0000000..4dfef47 --- /dev/null +++ b/Tools/Hazel-Networking/Hazel/Crypto/Const.cs @@ -0,0 +1,82 @@ +using System.Diagnostics; + +namespace Hazel.Crypto +{ + public static class Const + { + + /// <summary> + /// Compare two bytes for equality. + /// + /// This takes care to always use a constant amount of time to prevent + /// leaking information through side-channel attacks. + /// + /// This is aceived by collapsing the xor bits down into a single bit. + /// + /// Ported from: + /// https://github.com/mendsley/tiny/blob/master/include/tiny/crypto/constant.h + /// </summary> + /// <returns> + /// Returns `1` is the two bytes or equivalent. Otherwise, returns `0` + /// </returns> + public static byte ConstantCompareByte(byte a, byte b) + { + byte result = (byte)(~(a ^ b)); + + // collapse bits down to the LSB + result &= (byte)(result >> 4); + result &= (byte)(result >> 2); + result &= (byte)(result >> 1); + + return result; + } + + /// <summary> + /// Compare two equal length spans for equality. + /// + /// This takes care to always use a constant amount of time to prevent + /// leaking information through side-channel attacks. + /// + /// Ported from: + /// https://github.com/mendsley/tiny/blob/master/include/tiny/crypto/constant.h + /// </summary> + /// <returns> + /// Returns `1` if the spans are equivalent. Others, returns `0`. + /// </returns> + public static byte ConstantCompareSpans(ByteSpan a, ByteSpan b) + { + Debug.Assert(a.Length == b.Length); + + byte value = 0; + for (int ii = 0, nn = a.Length; ii != nn; ++ii) + { + value |= (byte)(a[ii] ^ b[ii]); + } + + return ConstantCompareByte(value, 0); + } + + /// <summary> + /// Compare a span against an all zero span + /// + /// This takes care to always use a constant amount of time to prevent + /// leaking information through side-channel attacks. + /// + /// Ported from: + /// https://github.com/mendsley/tiny/blob/master/include/tiny/crypto/constant.h + /// </summary> + /// <returns> + /// Returns `1` if the spans is all zeros. Others, returns `0`. + /// </returns> + public static byte ConstantCompareZeroSpan(ByteSpan a) + { + byte value = 0; + for (int ii = 0, nn = a.Length; ii != nn; ++ii) + { + value |= (byte)(a[ii] ^ 0); + } + + return ConstantCompareByte(value, 0); + } + } +} |