diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2022-11-20 01:53:05 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2022-11-20 01:53:05 +0700 |
commit | 63aad6ee7166ab55decdbc9d3e3110e7b10ce216 (patch) | |
tree | 836b027dcbc36142102f673f610ba3fc287a249e /crypto/src/math/ec/rfc8032/Wnaf.cs | |
parent | Use BitOperations for clz, ctz (diff) | |
download | BouncyCastle.NET-ed25519-63aad6ee7166ab55decdbc9d3e3110e7b10ce216.tar.xz |
Factor Wnaf out of EdDSA
Diffstat (limited to '')
-rw-r--r-- | crypto/src/math/ec/rfc8032/Wnaf.cs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/crypto/src/math/ec/rfc8032/Wnaf.cs b/crypto/src/math/ec/rfc8032/Wnaf.cs new file mode 100644 index 000000000..cc6e3704f --- /dev/null +++ b/crypto/src/math/ec/rfc8032/Wnaf.cs @@ -0,0 +1,65 @@ +using System; +using System.Diagnostics; + +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Math.EC.Rfc8032 +{ + internal static class Wnaf + { +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + internal static void GetSignedVar(ReadOnlySpan<uint> n, int width, Span<sbyte> ws) +#else + internal static void GetSignedVar(uint[] n, int width, sbyte[] ws) +#endif + { + Debug.Assert(2 <= width && width <= 8); + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + Span<uint> t = n.Length <= 64 + ? stackalloc uint[n.Length * 2] + : new uint[n.Length * 2]; +#else + uint[] t = new uint[n.Length * 2]; +#endif + { + uint c = 0U - (n[n.Length - 1] >> 31); + int tPos = t.Length, i = n.Length; + while (--i >= 0) + { + uint next = n[i]; + t[--tPos] = (next >> 16) | (c << 16); + t[--tPos] = c = next; + } + } + + uint sign = 0U; + int j = 0, lead = 32 - width; + + for (int i = 0; i < t.Length; ++i, j -= 16) + { + uint word = t[i]; + while (j < 16) + { + uint word16 = word >> j; + + int skip = Integers.NumberOfTrailingZeros((int)((sign ^ word16) | 0xFFFF0000U)); + if (skip > 0) + { + j += skip; + continue; + } + + int digit = ((int)word16 | 1) << lead; + sign = (uint)(digit >> 31); + + ws[(i << 4) + j] = (sbyte)(digit >> lead); + + j += width; + } + } + + Debug.Assert(sign == n[n.Length - 1] >> 31); + } + } +} |