diff options
author | Peter Dettman <peter.dettman@bouncycastle.org> | 2022-10-04 19:44:44 +0700 |
---|---|---|
committer | Peter Dettman <peter.dettman@bouncycastle.org> | 2022-10-04 19:44:44 +0700 |
commit | 286b626903b2e3de5610b6cdff9ec196fcf2244e (patch) | |
tree | d1200531c206693630dc7edd0182cdee2342ecc4 /crypto/src/math/ec/rfc7748/X25519.cs | |
parent | Avoid some allocations around MPInteger (diff) | |
download | BouncyCastle.NET-ed25519-286b626903b2e3de5610b6cdff9ec196fcf2244e.tar.xz |
Span-based variants for XDH/EdDSA
Diffstat (limited to 'crypto/src/math/ec/rfc7748/X25519.cs')
-rw-r--r-- | crypto/src/math/ec/rfc7748/X25519.cs | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/crypto/src/math/ec/rfc7748/X25519.cs b/crypto/src/math/ec/rfc7748/X25519.cs index 2a471ae26..954b2dd90 100644 --- a/crypto/src/math/ec/rfc7748/X25519.cs +++ b/crypto/src/math/ec/rfc7748/X25519.cs @@ -80,18 +80,42 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 public static void GeneratePrivateKey(SecureRandom random, byte[] k) { + if (k.Length != ScalarSize) + throw new ArgumentException(nameof(k)); + + random.NextBytes(k); + + k[0] &= 0xF8; + k[ScalarSize - 1] &= 0x7F; + k[ScalarSize - 1] |= 0x40; + } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public static void GeneratePrivateKey(SecureRandom random, Span<byte> k) + { + if (k.Length != ScalarSize) + throw new ArgumentException(nameof(k)); + random.NextBytes(k); k[0] &= 0xF8; k[ScalarSize - 1] &= 0x7F; k[ScalarSize - 1] |= 0x40; } +#endif public static void GeneratePublicKey(byte[] k, int kOff, byte[] r, int rOff) { ScalarMultBase(k, kOff, r, rOff); } +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public static void GeneratePublicKey(ReadOnlySpan<byte> k, Span<byte> r) + { + ScalarMultBase(k, r); + } +#endif + private static void PointDouble(int[] x, int[] z) { int[] a = F.Create(); @@ -255,5 +279,23 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 F.Normalize(y); F.Encode(y, r, rOff); } + +#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER + public static void ScalarMultBase(ReadOnlySpan<byte> k, Span<byte> r) + { + int[] y = F.Create(); + int[] z = F.Create(); + + Ed25519.ScalarMultBaseYZ(k, y, z); + + F.Apm(z, y, y, z); + + F.Inv(z, z); + F.Mul(y, z, y); + + F.Normalize(y); + F.Encode(y, r); + } +#endif } } |