diff options
78 files changed, 4032 insertions, 726 deletions
diff --git a/crypto/Readme.html b/crypto/Readme.html index c05560d93..9f4705f00 100644 --- a/crypto/Readme.html +++ b/crypto/Readme.html @@ -301,6 +301,7 @@ We state, where EC MQV has not otherwise been disabled or removed: <li>Further work has been done on improving SHA-3 performance.</li> <li>EC key generation and signing now use cache-timing resistant table lookups.</li> <li>RFC 7748: Added low-level implementations of X25519 and X448.</li> + <li>RFC 8032: Added low-level implementations of Ed25519 and Ed448.</li> </ul> <h5>Additional Notes</h5> <ul> diff --git a/crypto/crypto.csproj b/crypto/crypto.csproj index d0afb9f14..7cd8de821 100644 --- a/crypto/crypto.csproj +++ b/crypto/crypto.csproj @@ -6154,6 +6154,11 @@ BuildAction = "Compile" /> <File + RelPath = "src\math\ec\multiplier\IPreCompCallback.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "src\math\ec\multiplier\MixedNafR2LMultiplier.cs" SubType = "Code" BuildAction = "Compile" @@ -6184,6 +6189,11 @@ BuildAction = "Compile" /> <File + RelPath = "src\math\ec\multiplier\ValidityPreCompInfo.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "src\math\ec\multiplier\WNafL2RMultiplier.cs" SubType = "Code" BuildAction = "Compile" @@ -6239,6 +6249,16 @@ BuildAction = "Compile" /> <File + RelPath = "src\math\ec\rfc8032\Ed25519.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File + RelPath = "src\math\ec\rfc8032\Ed448.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "src\math\field\FiniteFields.cs" SubType = "Code" BuildAction = "Compile" @@ -12340,6 +12360,16 @@ BuildAction = "Compile" /> <File + RelPath = "test\src\math\ec\rfc8032\test\Ed25519Test.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File + RelPath = "test\src\math\ec\rfc8032\test\Ed448Test.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "test\src\math\ec\test\AllTests.cs" SubType = "Code" BuildAction = "Compile" diff --git a/crypto/src/asn1/cryptopro/ECGOST3410NamedCurves.cs b/crypto/src/asn1/cryptopro/ECGOST3410NamedCurves.cs index 9c366503d..b61da6b57 100644 --- a/crypto/src/asn1/cryptopro/ECGOST3410NamedCurves.cs +++ b/crypto/src/asn1/cryptopro/ECGOST3410NamedCurves.cs @@ -32,15 +32,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), // a new BigInteger("166"), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ECDomainParameters ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("1"), // x new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612")), // y - mod_q); + mod_q, BigInteger.One); parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProA] = ecParams; @@ -51,15 +50,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), new BigInteger("166"), - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("1"), // x new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612")), // y - mod_q); + mod_q, BigInteger.One); parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchA] = ecParams; @@ -70,15 +68,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823190"), // a new BigInteger("28091019353058090096996979000309560759124368558014865957655842872397301267595"), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("1"), // x new BigInteger("28792665814854611296992347458380284135028636778229113005756334730996303888124")), // y - mod_q); // q + mod_q, BigInteger.One); parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProB] = ecParams; @@ -89,15 +86,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"), new BigInteger("32858"), - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("0"), new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247")), - mod_q); + mod_q, BigInteger.One); parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProXchB] = ecParams; @@ -107,15 +103,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"), // a new BigInteger("32858"), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("0"), // x new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247")), // y - mod_q); // q + mod_q, BigInteger.One); parameters[CryptoProObjectIdentifiers.GostR3410x2001CryptoProC] = ecParams; @@ -126,15 +121,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), // a new BigInteger("166"), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("1"), // x new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612")), // y - mod_q); // q + mod_q, BigInteger.One); parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256_paramSetA] = ecParams; @@ -144,15 +138,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDC4",16), // a new BigInteger("E8C2505DEDFC86DDC1BD0B2B6667F1DA34B82574761CB0E879BD081CFD0B6265EE3CB090F30D27614CB4574010DA90DD862EF9D4EBEE4761503190785A71C760",16), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003"), // x new BigInteger("7503CFE87A836AE3A61B8816E25450E6CE5E1C93ACF1ABC1778064FDCBEFA921DF1626BE4FD036E93D75E6A50E3A41E98028FE5FC235F5B889A589CB5215F2A4",16)), // y - mod_q); // q + mod_q, BigInteger.One); parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetA] = ecParams; @@ -162,15 +155,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006C",16), // a new BigInteger("687D1B459DC841457E3E06CF6F5E2517B97C7D614AF138BCBF85DC806C4B289F3E965D2DB1416D217F8B276FAD1AB69C50F78BEE1FA3106EFB8CCBC7C5140116",16), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002"), // x new BigInteger("1A8F7EDA389B094C2C071E3647A8940F3C123B697578C213BE6DD9E6C8EC7335DCB228FD1EDF4A39152CBCAAF8C0398828041055F94CEEEC7E21340780FE41BD",16)), // y - mod_q); // q + mod_q, BigInteger.One); parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetB] = ecParams; @@ -180,15 +172,14 @@ namespace Org.BouncyCastle.Asn1.CryptoPro mod_p, // p new BigInteger("DC9203E514A721875485A529D2C722FB187BC8980EB866644DE41C68E143064546E861C0E2C9EDD92ADE71F46FCF50FF2AD97F951FDA9F2A2EB6546F39689BD3",16), // a new BigInteger("B4C4EE28CEBC6C2C8AC12952CF37F16AC7EFB6A9F69F4B57FFDA2E4F0DE5ADE038CBC2FFF719D2C18DE0284B8BFEF3B52B8CC7A5F5BF0A3C8D2319A5312557E1",16), // b - mod_q, - BigInteger.One); + mod_q, BigInteger.One); ecParams = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("E2E31EDFC23DE7BDEBE241CE593EF5DE2295B7A9CBAEF021D385F7074CEA043AA27272A7AE602BF2A7B9033DB9ED3610C6FB85487EAE97AAC5BC7928C1950148", 16), // x new BigInteger("F5CE40D95B5EB899ABBCCFF5911CB8577939804D6527378B8C108C3D2090FF9BE18E2D33E3021ED2EF32D85822423B6304F726AA854BAE07D0396E9A9ADDC40F",16)), // y - mod_q); // q + mod_q, BigInteger.One); parameters[RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512_paramSetC] = ecParams; diff --git a/crypto/src/asn1/x9/X962NamedCurves.cs b/crypto/src/asn1/x9/X962NamedCurves.cs index 14f7f818a..1609774f1 100644 --- a/crypto/src/asn1/x9/X962NamedCurves.cs +++ b/crypto/src/asn1/x9/X962NamedCurves.cs @@ -31,7 +31,7 @@ namespace Org.BouncyCastle.Asn1.X9 BigInteger h = BigInteger.One; ECCurve cFp192v1 = new FpCurve( - new BigInteger("6277101735386680763835789423207666416083908700390324961279"), + new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16), n, h); @@ -58,7 +58,7 @@ namespace Org.BouncyCastle.Asn1.X9 BigInteger h = BigInteger.One; ECCurve cFp192v2 = new FpCurve( - new BigInteger("6277101735386680763835789423207666416083908700390324961279"), + new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("cc22d6dfb95c6b25e49c0d6364a4e5980c393aa21668d953", 16), n, h); @@ -85,7 +85,7 @@ namespace Org.BouncyCastle.Asn1.X9 BigInteger h = BigInteger.One; ECCurve cFp192v3 = new FpCurve( - new BigInteger("6277101735386680763835789423207666416083908700390324961279"), + new BigInteger("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", 16), new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), new BigInteger("22123dc2395a05caa7423daeccc94760a7d462256bd56916", 16), n, h); diff --git a/crypto/src/asn1/x9/X9Curve.cs b/crypto/src/asn1/x9/X9Curve.cs index f05a946c2..eab94def8 100644 --- a/crypto/src/asn1/x9/X9Curve.cs +++ b/crypto/src/asn1/x9/X9Curve.cs @@ -47,9 +47,19 @@ namespace Org.BouncyCastle.Asn1.X9 } } + [Obsolete("Use constructor including order/cofactor")] public X9Curve( X9FieldID fieldID, Asn1Sequence seq) + : this(fieldID, null, null, seq) + { + } + + public X9Curve( + X9FieldID fieldID, + BigInteger order, + BigInteger cofactor, + Asn1Sequence seq) { if (fieldID == null) throw new ArgumentNullException("fieldID"); @@ -60,47 +70,47 @@ namespace Org.BouncyCastle.Asn1.X9 if (fieldIdentifier.Equals(X9ObjectIdentifiers.PrimeField)) { - BigInteger q = ((DerInteger) fieldID.Parameters).Value; - X9FieldElement x9A = new X9FieldElement(q, (Asn1OctetString) seq[0]); - X9FieldElement x9B = new X9FieldElement(q, (Asn1OctetString) seq[1]); - curve = new FpCurve(q, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger()); + BigInteger p = ((DerInteger)fieldID.Parameters).Value; + BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets()); + BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets()); + curve = new FpCurve(p, A, B, order, cofactor); } - else + else if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField)) { - if (fieldIdentifier.Equals(X9ObjectIdentifiers.CharacteristicTwoField)) + // Characteristic two field + DerSequence parameters = (DerSequence)fieldID.Parameters; + int m = ((DerInteger)parameters[0]).Value.IntValue; + DerObjectIdentifier representation + = (DerObjectIdentifier)parameters[1]; + + int k1 = 0; + int k2 = 0; + int k3 = 0; + if (representation.Equals(X9ObjectIdentifiers.TPBasis)) { - // Characteristic two field - DerSequence parameters = (DerSequence)fieldID.Parameters; - int m = ((DerInteger)parameters[0]).Value.IntValue; - DerObjectIdentifier representation - = (DerObjectIdentifier)parameters[1]; - - int k1 = 0; - int k2 = 0; - int k3 = 0; - if (representation.Equals(X9ObjectIdentifiers.TPBasis)) - { - // Trinomial basis representation - k1 = ((DerInteger)parameters[2]).Value.IntValue; - } - else - { - // Pentanomial basis representation - DerSequence pentanomial = (DerSequence) parameters[2]; - k1 = ((DerInteger) pentanomial[0]).Value.IntValue; - k2 = ((DerInteger) pentanomial[1]).Value.IntValue; - k3 = ((DerInteger) pentanomial[2]).Value.IntValue; - } - X9FieldElement x9A = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[0]); - X9FieldElement x9B = new X9FieldElement(m, k1, k2, k3, (Asn1OctetString)seq[1]); - // TODO Is it possible to get the order (n) and cofactor(h) too? - curve = new F2mCurve(m, k1, k2, k3, x9A.Value.ToBigInteger(), x9B.Value.ToBigInteger()); + // Trinomial basis representation + k1 = ((DerInteger)parameters[2]).Value.IntValue; } + else + { + // Pentanomial basis representation + DerSequence pentanomial = (DerSequence) parameters[2]; + k1 = ((DerInteger) pentanomial[0]).Value.IntValue; + k2 = ((DerInteger) pentanomial[1]).Value.IntValue; + k3 = ((DerInteger) pentanomial[2]).Value.IntValue; + } + BigInteger A = new BigInteger(1, Asn1OctetString.GetInstance(seq[0]).GetOctets()); + BigInteger B = new BigInteger(1, Asn1OctetString.GetInstance(seq[1]).GetOctets()); + curve = new F2mCurve(m, k1, k2, k3, A, B, order, cofactor); + } + else + { + throw new ArgumentException("This type of ECCurve is not implemented"); } if (seq.Count == 3) { - seed = ((DerBitString) seq[2]).GetBytes(); + seed = ((DerBitString)seq[2]).GetBytes(); } } diff --git a/crypto/src/asn1/x9/X9ECParameters.cs b/crypto/src/asn1/x9/X9ECParameters.cs index 0fa343768..e1b29ca13 100644 --- a/crypto/src/asn1/x9/X9ECParameters.cs +++ b/crypto/src/asn1/x9/X9ECParameters.cs @@ -23,29 +23,32 @@ namespace Org.BouncyCastle.Asn1.X9 public static X9ECParameters GetInstance(Object obj) { if (obj is X9ECParameters) - { return (X9ECParameters)obj; - } - if (obj != null) - { + if (obj != null) return new X9ECParameters(Asn1Sequence.GetInstance(obj)); - } - return null; + return null; } public X9ECParameters( Asn1Sequence seq) { if (!(seq[0] is DerInteger) - || !((DerInteger) seq[0]).Value.Equals(BigInteger.One)) + || !((DerInteger)seq[0]).Value.Equals(BigInteger.One)) { throw new ArgumentException("bad version in X9ECParameters"); } + this.n = ((DerInteger)seq[4]).Value; + + if (seq.Count == 6) + { + this.h = ((DerInteger)seq[5]).Value; + } + X9Curve x9c = new X9Curve( - X9FieldID.GetInstance(seq[1]), + X9FieldID.GetInstance(seq[1]), n, h, Asn1Sequence.GetInstance(seq[2])); this.curve = x9c.Curve; @@ -53,20 +56,14 @@ namespace Org.BouncyCastle.Asn1.X9 if (p is X9ECPoint) { - this.g = ((X9ECPoint)p); + this.g = (X9ECPoint)p; } else { this.g = new X9ECPoint(curve, (Asn1OctetString)p); } - this.n = ((DerInteger)seq[4]).Value; this.seed = x9c.GetSeed(); - - if (seq.Count == 6) - { - this.h = ((DerInteger)seq[5]).Value; - } } public X9ECParameters( diff --git a/crypto/src/asn1/x9/X9FieldElement.cs b/crypto/src/asn1/x9/X9FieldElement.cs index 94bd96b24..222b4cfc8 100644 --- a/crypto/src/asn1/x9/X9FieldElement.cs +++ b/crypto/src/asn1/x9/X9FieldElement.cs @@ -19,6 +19,7 @@ namespace Org.BouncyCastle.Asn1.X9 this.f = f; } + [Obsolete("Will be removed")] public X9FieldElement( BigInteger p, Asn1OctetString s) @@ -26,6 +27,7 @@ namespace Org.BouncyCastle.Asn1.X9 { } + [Obsolete("Will be removed")] public X9FieldElement( int m, int k1, diff --git a/crypto/src/crypto/agreement/ECDHBasicAgreement.cs b/crypto/src/crypto/agreement/ECDHBasicAgreement.cs index ca7b3fa3f..1358db0cf 100644 --- a/crypto/src/crypto/agreement/ECDHBasicAgreement.cs +++ b/crypto/src/crypto/agreement/ECDHBasicAgreement.cs @@ -45,12 +45,26 @@ namespace Org.BouncyCastle.Crypto.Agreement public virtual BigInteger CalculateAgreement( ICipherParameters pubKey) { - ECPublicKeyParameters pub = (ECPublicKeyParameters) pubKey; - if (!pub.Parameters.Equals(privKey.Parameters)) + ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey; + ECDomainParameters dp = privKey.Parameters; + if (!dp.Equals(pub.Parameters)) throw new InvalidOperationException("ECDH public key has wrong domain parameters"); - ECPoint P = pub.Q.Multiply(privKey.D).Normalize(); + BigInteger d = privKey.D; + // Always perform calculations on the exact curve specified by our private key's parameters + ECPoint Q = ECAlgorithms.CleanPoint(dp.Curve, pub.Q); + if (Q.IsInfinity) + throw new InvalidOperationException("Infinity is not a valid public key for ECDH"); + + BigInteger h = dp.H; + if (!h.Equals(BigInteger.One)) + { + d = dp.HInv.Multiply(d).Mod(dp.N); + Q = ECAlgorithms.ReferenceMultiply(Q, h); + } + + ECPoint P = Q.Multiply(d).Normalize(); if (P.IsInfinity) throw new InvalidOperationException("Infinity is not a valid agreement value for ECDH"); diff --git a/crypto/src/crypto/agreement/ECDHCBasicAgreement.cs b/crypto/src/crypto/agreement/ECDHCBasicAgreement.cs index 1c9ae45f9..f0b5d1e02 100644 --- a/crypto/src/crypto/agreement/ECDHCBasicAgreement.cs +++ b/crypto/src/crypto/agreement/ECDHCBasicAgreement.cs @@ -50,15 +50,19 @@ namespace Org.BouncyCastle.Crypto.Agreement public virtual BigInteger CalculateAgreement( ICipherParameters pubKey) { - ECPublicKeyParameters pub = (ECPublicKeyParameters) pubKey; - ECDomainParameters parameters = pub.Parameters; - if (!parameters.Equals(privKey.Parameters)) + ECPublicKeyParameters pub = (ECPublicKeyParameters)pubKey; + ECDomainParameters dp = privKey.Parameters; + if (!dp.Equals(pub.Parameters)) throw new InvalidOperationException("ECDHC public key has wrong domain parameters"); - BigInteger hd = parameters.H.Multiply(privKey.D).Mod(parameters.N); + BigInteger hd = dp.H.Multiply(privKey.D).Mod(dp.N); - ECPoint P = pub.Q.Multiply(hd).Normalize(); + // Always perform calculations on the exact curve specified by our private key's parameters + ECPoint pubPoint = ECAlgorithms.CleanPoint(dp.Curve, pub.Q); + if (pubPoint.IsInfinity) + throw new InvalidOperationException("Infinity is not a valid public key for ECDHC"); + ECPoint P = pubPoint.Multiply(hd).Normalize(); if (P.IsInfinity) throw new InvalidOperationException("Infinity is not a valid agreement value for ECDHC"); diff --git a/crypto/src/crypto/agreement/ECMqvBasicAgreement.cs b/crypto/src/crypto/agreement/ECMqvBasicAgreement.cs index 8d5cebb13..b71f5a7d2 100644 --- a/crypto/src/crypto/agreement/ECMqvBasicAgreement.cs +++ b/crypto/src/crypto/agreement/ECMqvBasicAgreement.cs @@ -64,16 +64,9 @@ namespace Org.BouncyCastle.Crypto.Agreement ECCurve curve = parameters.Curve; - ECPoint[] points = new ECPoint[]{ - // The Q2U public key is optional - but will be calculated for us if it wasn't present - ECAlgorithms.ImportPoint(curve, Q2U.Q), - ECAlgorithms.ImportPoint(curve, Q1V.Q), - ECAlgorithms.ImportPoint(curve, Q2V.Q) - }; - - curve.NormalizeAll(points); - - ECPoint q2u = points[0], q1v = points[1], q2v = points[2]; + ECPoint q2u = ECAlgorithms.CleanPoint(curve, Q2U.Q); + ECPoint q1v = ECAlgorithms.CleanPoint(curve, Q1V.Q); + ECPoint q2v = ECAlgorithms.CleanPoint(curve, Q2V.Q); BigInteger x = q2u.AffineXCoord.ToBigInteger(); BigInteger xBar = x.Mod(powE); diff --git a/crypto/src/crypto/agreement/SM2KeyExchange.cs b/crypto/src/crypto/agreement/SM2KeyExchange.cs index 1cfcd6a3a..986d98421 100644 --- a/crypto/src/crypto/agreement/SM2KeyExchange.cs +++ b/crypto/src/crypto/agreement/SM2KeyExchange.cs @@ -144,8 +144,10 @@ namespace Org.BouncyCastle.Crypto.Agreement protected virtual ECPoint CalculateU(SM2KeyExchangePublicParameters otherPub) { - ECPoint p1 = otherPub.StaticPublicKey.Q; - ECPoint p2 = otherPub.EphemeralPublicKey.Q; + ECDomainParameters dp = mStaticKey.Parameters; + + ECPoint p1 = ECAlgorithms.CleanPoint(dp.Curve, otherPub.StaticPublicKey.Q); + ECPoint p2 = ECAlgorithms.CleanPoint(dp.Curve, otherPub.EphemeralPublicKey.Q); BigInteger x1 = Reduce(mEphemeralPubPoint.AffineXCoord.ToBigInteger()); BigInteger x2 = Reduce(p2.AffineXCoord.ToBigInteger()); diff --git a/crypto/src/crypto/engines/Cast5Engine.cs b/crypto/src/crypto/engines/Cast5Engine.cs index 53836db02..398f6d43a 100644 --- a/crypto/src/crypto/engines/Cast5Engine.cs +++ b/crypto/src/crypto/engines/Cast5Engine.cs @@ -20,7 +20,7 @@ namespace Org.BouncyCastle.Crypto.Engines public class Cast5Engine : IBlockCipher { - internal static readonly uint[] S1 = + private static readonly uint[] S1 = { 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, diff --git a/crypto/src/crypto/engines/IdeaEngine.cs b/crypto/src/crypto/engines/IdeaEngine.cs index 18a151c93..6c0379174 100644 --- a/crypto/src/crypto/engines/IdeaEngine.cs +++ b/crypto/src/crypto/engines/IdeaEngine.cs @@ -9,24 +9,14 @@ namespace Org.BouncyCastle.Crypto.Engines * A class that provides a basic International Data Encryption Algorithm (IDEA) engine. * <p> * This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM" - * implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (baring 1 typo at the - * end of the mulinv function!). + * implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (barring 1 typo at the + * end of the MulInv function!). * </p> * <p> * It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/ * </p> * <p> - * Note 1: This algorithm is patented in the USA, Japan, and Europe including - * at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland - * and the United Kingdom. Non-commercial use is free, however any commercial - * products are liable for royalties. Please see - * <a href="http://www.mediacrypt.com">www.mediacrypt.com</a> for - * further details. This announcement has been included at the request of - * the patent holders. - * </p> - * <p> - * Note 2: Due to the requests concerning the above, this algorithm is now only - * included in the extended assembly. It is not included in the default distributions. + * Note: This algorithm was patented in the USA, Japan and Europe. These patents expired in 2011/2012. * </p> */ public class IdeaEngine diff --git a/crypto/src/crypto/parameters/ECDomainParameters.cs b/crypto/src/crypto/parameters/ECDomainParameters.cs index 732fbdfa4..e377f7760 100644 --- a/crypto/src/crypto/parameters/ECDomainParameters.cs +++ b/crypto/src/crypto/parameters/ECDomainParameters.cs @@ -13,12 +13,13 @@ namespace Org.BouncyCastle.Crypto.Parameters internal ECPoint g; internal BigInteger n; internal BigInteger h; + internal BigInteger hInv; public ECDomainParameters( ECCurve curve, ECPoint g, BigInteger n) - : this(curve, g, n, BigInteger.One) + : this(curve, g, n, BigInteger.One, null) { } @@ -44,11 +45,10 @@ namespace Org.BouncyCastle.Crypto.Parameters throw new ArgumentNullException("g"); if (n == null) throw new ArgumentNullException("n"); - if (h == null) - throw new ArgumentNullException("h"); + // we can't check for h == null here as h is optional in X9.62 as it is not required for ECDSA this.curve = curve; - this.g = g.Normalize(); + this.g = Validate(curve, g); this.n = n; this.h = h; this.seed = Arrays.Clone(seed); @@ -74,6 +74,21 @@ namespace Org.BouncyCastle.Crypto.Parameters get { return h; } } + public BigInteger HInv + { + get + { + lock (this) + { + if (hInv == null) + { + hInv = h.ModInverse(n); + } + return hInv; + } + } + } + public byte[] GetSeed() { return Arrays.Clone(seed); @@ -99,7 +114,7 @@ namespace Org.BouncyCastle.Crypto.Parameters return curve.Equals(other.curve) && g.Equals(other.g) && n.Equals(other.n) - && h.Equals(other.h); + && h.Equals(other.h); } public override int GetHashCode() @@ -113,5 +128,21 @@ namespace Org.BouncyCastle.Crypto.Parameters hc ^= h.GetHashCode(); return hc; } + + internal static ECPoint Validate(ECCurve c, ECPoint q) + { + if (q == null) + throw new ArgumentException("Point has null value", "q"); + + q = ECAlgorithms.ImportPoint(c, q).Normalize(); + + if (q.IsInfinity) + throw new ArgumentException("Point at infinity", "q"); + + if (!q.IsValid()) + throw new ArgumentException("Point not on curve", "q"); + + return q; + } } } diff --git a/crypto/src/crypto/parameters/ECPublicKeyParameters.cs b/crypto/src/crypto/parameters/ECPublicKeyParameters.cs index 474e5d82c..69916e525 100644 --- a/crypto/src/crypto/parameters/ECPublicKeyParameters.cs +++ b/crypto/src/crypto/parameters/ECPublicKeyParameters.cs @@ -9,21 +9,6 @@ namespace Org.BouncyCastle.Crypto.Parameters public class ECPublicKeyParameters : ECKeyParameters { - private static ECPoint Validate(ECPoint q) - { - if (q == null) - throw new ArgumentNullException("q"); - if (q.IsInfinity) - throw new ArgumentException("point at infinity", "q"); - - q = q.Normalize(); - - if (!q.IsValid()) - throw new ArgumentException("point not on curve", "q"); - - return q; - } - private readonly ECPoint q; public ECPublicKeyParameters( @@ -42,7 +27,7 @@ namespace Org.BouncyCastle.Crypto.Parameters if (q == null) throw new ArgumentNullException("q"); - this.q = Validate(q); + this.q = ECDomainParameters.Validate(Parameters.Curve, q); } public ECPublicKeyParameters( @@ -54,7 +39,7 @@ namespace Org.BouncyCastle.Crypto.Parameters if (q == null) throw new ArgumentNullException("q"); - this.q = Validate(q); + this.q = ECDomainParameters.Validate(Parameters.Curve, q); } public ECPublicKeyParameters( @@ -66,7 +51,7 @@ namespace Org.BouncyCastle.Crypto.Parameters if (q == null) throw new ArgumentNullException("q"); - this.q = Validate(q); + this.q = ECDomainParameters.Validate(Parameters.Curve, q); } public ECPoint Q diff --git a/crypto/src/math/ec/ECAlgorithms.cs b/crypto/src/math/ec/ECAlgorithms.cs index 5d60de40f..b05c0201a 100644 --- a/crypto/src/math/ec/ECAlgorithms.cs +++ b/crypto/src/math/ec/ECAlgorithms.cs @@ -58,10 +58,10 @@ namespace Org.BouncyCastle.Math.EC GlvEndomorphism glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { - return ValidatePoint(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism)); + return ImplCheckResult(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism)); } - return ValidatePoint(ImplSumOfMultiplies(imported, ks)); + return ImplCheckResult(ImplSumOfMultiplies(imported, ks)); } public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b) @@ -74,18 +74,18 @@ namespace Org.BouncyCastle.Math.EC AbstractF2mCurve f2mCurve = cp as AbstractF2mCurve; if (f2mCurve != null && f2mCurve.IsKoblitz) { - return ValidatePoint(P.Multiply(a).Add(Q.Multiply(b))); + return ImplCheckResult(P.Multiply(a).Add(Q.Multiply(b))); } } GlvEndomorphism glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { - return ValidatePoint( + return ImplCheckResult( ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism)); } - return ValidatePoint(ImplShamirsTrickWNaf(P, a, Q, b)); + return ImplCheckResult(ImplShamirsTrickWNaf(P, a, Q, b)); } /* @@ -111,7 +111,7 @@ namespace Org.BouncyCastle.Math.EC ECCurve cp = P.Curve; Q = ImportPoint(cp, Q); - return ValidatePoint(ImplShamirsTrickJsf(P, k, Q, l)); + return ImplCheckResult(ImplShamirsTrickJsf(P, k, Q, l)); } public static ECPoint ImportPoint(ECCurve c, ECPoint p) @@ -202,7 +202,24 @@ namespace Org.BouncyCastle.Math.EC public static ECPoint ValidatePoint(ECPoint p) { if (!p.IsValid()) - throw new ArgumentException("Invalid point", "p"); + throw new InvalidOperationException("Invalid point"); + + return p; + } + + public static ECPoint CleanPoint(ECCurve c, ECPoint p) + { + ECCurve cp = p.Curve; + if (!c.Equals(cp)) + throw new ArgumentException("Point must be on the same curve", "p"); + + return c.DecodePoint(p.GetEncoded(false)); + } + + internal static ECPoint ImplCheckResult(ECPoint p) + { + if (!p.IsValidPartial()) + throw new InvalidOperationException("Invalid result"); return p; } diff --git a/crypto/src/math/ec/ECCurve.cs b/crypto/src/math/ec/ECCurve.cs index 6a9342722..993b69149 100644 --- a/crypto/src/math/ec/ECCurve.cs +++ b/crypto/src/math/ec/ECCurve.cs @@ -161,15 +161,24 @@ namespace Org.BouncyCastle.Math.EC public virtual PreCompInfo GetPreCompInfo(ECPoint point, string name) { CheckPoint(point); + + IDictionary table; lock (point) { - IDictionary table = point.m_preCompTable; - return table == null ? null : (PreCompInfo)table[name]; + table = point.m_preCompTable; + } + + if (null == table) + return null; + + lock (table) + { + return (PreCompInfo)table[name]; } } /** - * Adds <code>PreCompInfo</code> for a point on this curve, under a given name. Used by + * Compute a <code>PreCompInfo</code> for a point on this curve, under a given name. Used by * <code>ECMultiplier</code>s to save the precomputation for this <code>ECPoint</code> for use * by subsequent multiplication. * @@ -177,20 +186,34 @@ namespace Org.BouncyCastle.Math.EC * The <code>ECPoint</code> to store precomputations for. * @param name * A <code>String</code> used to index precomputations of different types. - * @param preCompInfo - * The values precomputed by the <code>ECMultiplier</code>. + * @param callback + * Called to calculate the <code>PreCompInfo</code>. */ - public virtual void SetPreCompInfo(ECPoint point, string name, PreCompInfo preCompInfo) + public virtual PreCompInfo Precompute(ECPoint point, string name, IPreCompCallback callback) { CheckPoint(point); + + IDictionary table; lock (point) { - IDictionary table = point.m_preCompTable; + table = point.m_preCompTable; if (null == table) { point.m_preCompTable = table = Platform.CreateHashtable(4); } - table[name] = preCompInfo; + } + + lock (table) + { + PreCompInfo existing = (PreCompInfo)table[name]; + PreCompInfo result = callback.Precompute(existing); + + if (result != existing) + { + table[name] = result; + } + + return result; } } @@ -208,7 +231,7 @@ namespace Org.BouncyCastle.Math.EC // TODO Default behaviour could be improved if the two curves have the same coordinate system by copying any Z coordinates. p = p.Normalize(); - return ValidatePoint(p.XCoord.ToBigInteger(), p.YCoord.ToBigInteger(), p.IsCompressed); + return CreatePoint(p.XCoord.ToBigInteger(), p.YCoord.ToBigInteger(), p.IsCompressed); } /** @@ -453,7 +476,7 @@ namespace Org.BouncyCastle.Math.EC BigInteger X = new BigInteger(1, encoded, 1, expectedLength); p = DecompressPoint(yTilde, X); - if (!p.SatisfiesCofactor()) + if (!p.ImplIsValid(true, true)) throw new ArgumentException("Invalid point"); break; @@ -588,6 +611,7 @@ namespace Org.BouncyCastle.Math.EC protected readonly BigInteger m_q, m_r; protected readonly FpPoint m_infinity; + [Obsolete("Use constructor taking order/cofactor")] public FpCurve(BigInteger q, BigInteger a, BigInteger b) : this(q, a, b, null, null) { @@ -598,7 +622,7 @@ namespace Org.BouncyCastle.Math.EC { this.m_q = q; this.m_r = FpFieldElement.CalculateResidue(q); - this.m_infinity = new FpPoint(this, null, null); + this.m_infinity = new FpPoint(this, null, null, false); this.m_a = FromBigInteger(a); this.m_b = FromBigInteger(b); @@ -607,6 +631,7 @@ namespace Org.BouncyCastle.Math.EC this.m_coord = FP_DEFAULT_COORDS; } + [Obsolete("Use constructor taking order/cofactor")] protected FpCurve(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b) : this(q, r, a, b, null, null) { @@ -617,7 +642,7 @@ namespace Org.BouncyCastle.Math.EC { this.m_q = q; this.m_r = r; - this.m_infinity = new FpPoint(this, null, null); + this.m_infinity = new FpPoint(this, null, null, false); this.m_a = a; this.m_b = b; @@ -794,7 +819,7 @@ namespace Org.BouncyCastle.Math.EC else { ECFieldElement beta = xp.Square().Invert().Multiply(B).Add(A).Add(xp); - ECFieldElement z = SolveQuadradicEquation(beta); + ECFieldElement z = SolveQuadraticEquation(beta); if (z != null) { @@ -831,11 +856,11 @@ namespace Org.BouncyCastle.Math.EC * D.1.6) The other solution is <code>z + 1</code>. * * @param beta - * The value to solve the qradratic equation for. + * The value to solve the quadratic equation for. * @return the solution for <code>z<sup>2</sup> + z = beta</code> or * <code>null</code> if no solution exists. */ - private ECFieldElement SolveQuadradicEquation(ECFieldElement beta) + internal ECFieldElement SolveQuadraticEquation(ECFieldElement beta) { if (beta.IsZero) return beta; @@ -957,6 +982,7 @@ namespace Org.BouncyCastle.Math.EC * for non-supersingular elliptic curves over * <code>F<sub>2<sup>m</sup></sub></code>. */ + [Obsolete("Use constructor taking order/cofactor")] public F2mCurve( int m, int k, @@ -1014,6 +1040,7 @@ namespace Org.BouncyCastle.Math.EC * for non-supersingular elliptic curves over * <code>F<sub>2<sup>m</sup></sub></code>. */ + [Obsolete("Use constructor taking order/cofactor")] public F2mCurve( int m, int k1, @@ -1065,7 +1092,7 @@ namespace Org.BouncyCastle.Math.EC this.k3 = k3; this.m_order = order; this.m_cofactor = cofactor; - this.m_infinity = new F2mPoint(this, null, null); + this.m_infinity = new F2mPoint(this, null, null, false); if (k1 == 0) throw new ArgumentException("k1 must be > 0"); @@ -1099,7 +1126,7 @@ namespace Org.BouncyCastle.Math.EC this.m_order = order; this.m_cofactor = cofactor; - this.m_infinity = new F2mPoint(this, null, null); + this.m_infinity = new F2mPoint(this, null, null, false); this.m_a = a; this.m_b = b; this.m_coord = F2M_DEFAULT_COORDS; @@ -1188,18 +1215,6 @@ namespace Org.BouncyCastle.Math.EC get { return k3; } } - [Obsolete("Use 'Order' property instead")] - public BigInteger N - { - get { return m_order; } - } - - [Obsolete("Use 'Cofactor' property instead")] - public BigInteger H - { - get { return m_cofactor; } - } - public override ECLookupTable CreateCacheSafeLookupTable(ECPoint[] points, int off, int len) { int FE_LONGS = (m + 63) / 64; diff --git a/crypto/src/math/ec/ECFieldElement.cs b/crypto/src/math/ec/ECFieldElement.cs index 3676c81b1..350e8c6d4 100644 --- a/crypto/src/math/ec/ECFieldElement.cs +++ b/crypto/src/math/ec/ECFieldElement.cs @@ -101,9 +101,14 @@ namespace Org.BouncyCastle.Math.EC } } - public class FpFieldElement + public abstract class AbstractFpFieldElement : ECFieldElement { + } + + public class FpFieldElement + : AbstractFpFieldElement + { private readonly BigInteger q, r, x; internal static BigInteger CalculateResidue(BigInteger p) @@ -536,6 +541,45 @@ namespace Org.BouncyCastle.Math.EC } } + public abstract class AbstractF2mFieldElement + : ECFieldElement + { + public virtual ECFieldElement HalfTrace() + { + int m = FieldSize; + if ((m & 1) == 0) + throw new InvalidOperationException("Half-trace only defined for odd m"); + + ECFieldElement fe = this; + ECFieldElement ht = fe; + for (int i = 2; i < m; i += 2) + { + fe = fe.SquarePow(2); + ht = ht.Add(fe); + } + + return ht; + } + + public virtual int Trace() + { + int m = FieldSize; + ECFieldElement fe = this; + ECFieldElement tr = fe; + for (int i = 1; i < m; ++i) + { + fe = fe.Square(); + tr = tr.Add(fe); + } + if (tr.IsZero) + return 0; + if (tr.IsOne) + return 1; + + throw new InvalidOperationException("Internal error in trace calculation"); + } + } + /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) @@ -544,7 +588,7 @@ namespace Org.BouncyCastle.Math.EC * representation is not supported. */ public class F2mFieldElement - : ECFieldElement + : AbstractF2mFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen @@ -582,20 +626,21 @@ namespace Org.BouncyCastle.Math.EC internal LongArray x; /** - * Constructor for Ppb. - * @param m The exponent <code>m</code> of - * <code>F<sub>2<sup>m</sup></sub></code>. - * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + - * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> - * represents the reduction polynomial <code>f(z)</code>. - * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + - * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> - * represents the reduction polynomial <code>f(z)</code>. - * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + - * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> - * represents the reduction polynomial <code>f(z)</code>. - * @param x The BigInteger representing the value of the field element. - */ + * Constructor for Ppb. + * @param m The exponent <code>m</code> of + * <code>F<sub>2<sup>m</sup></sub></code>. + * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> + * represents the reduction polynomial <code>f(z)</code>. + * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> + * represents the reduction polynomial <code>f(z)</code>. + * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> + * represents the reduction polynomial <code>f(z)</code>. + * @param x The BigInteger representing the value of the field element. + */ + [Obsolete("Use ECCurve.FromBigInteger to construct field elements")] public F2mFieldElement( int m, int k1, @@ -627,14 +672,15 @@ namespace Org.BouncyCastle.Math.EC } /** - * Constructor for Tpb. - * @param m The exponent <code>m</code> of - * <code>F<sub>2<sup>m</sup></sub></code>. - * @param k The integer <code>k</code> where <code>x<sup>m</sup> + - * x<sup>k</sup> + 1</code> represents the reduction - * polynomial <code>f(z)</code>. - * @param x The BigInteger representing the value of the field element. - */ + * Constructor for Tpb. + * @param m The exponent <code>m</code> of + * <code>F<sub>2<sup>m</sup></sub></code>. + * @param k The integer <code>k</code> where <code>x<sup>m</sup> + + * x<sup>k</sup> + 1</code> represents the reduction + * polynomial <code>f(z)</code>. + * @param x The BigInteger representing the value of the field element. + */ + [Obsolete("Use ECCurve.FromBigInteger to construct field elements")] public F2mFieldElement( int m, int k, diff --git a/crypto/src/math/ec/ECPoint.cs b/crypto/src/math/ec/ECPoint.cs index a5ba515c5..2acc9f5c0 100644 --- a/crypto/src/math/ec/ECPoint.cs +++ b/crypto/src/math/ec/ECPoint.cs @@ -67,13 +67,19 @@ namespace Org.BouncyCastle.Math.EC this.m_withCompression = withCompression; } - protected internal bool SatisfiesCofactor() + protected abstract bool SatisfiesCurveEquation(); + + protected virtual bool SatisfiesOrder() { - BigInteger h = Curve.Cofactor; - return h == null || h.Equals(BigInteger.One) || !ECAlgorithms.ReferenceMultiply(this, h).IsInfinity; - } + if (BigInteger.One.Equals(Curve.Cofactor)) + return true; - protected abstract bool SatisfiesCurveEquation(); + BigInteger n = Curve.Order; + + // TODO Require order to be available for all curves + + return n == null || ECAlgorithms.ReferenceMultiply(this, n).IsInfinity; + } public ECPoint GetDetachedPoint() { @@ -97,30 +103,6 @@ namespace Org.BouncyCastle.Math.EC } /** - * Normalizes this point, and then returns the affine x-coordinate. - * - * Note: normalization can be expensive, this method is deprecated in favour - * of caller-controlled normalization. - */ - [Obsolete("Use AffineXCoord, or Normalize() and XCoord, instead")] - public virtual ECFieldElement X - { - get { return Normalize().XCoord; } - } - - /** - * Normalizes this point, and then returns the affine y-coordinate. - * - * Note: normalization can be expensive, this method is deprecated in favour - * of caller-controlled normalization. - */ - [Obsolete("Use AffineYCoord, or Normalize() and YCoord, instead")] - public virtual ECFieldElement Y - { - get { return Normalize().YCoord; } - } - - /** * Returns the affine x-coordinate after checking that this point is normalized. * * @return The affine x-coordinate of this point @@ -299,22 +281,22 @@ namespace Org.BouncyCastle.Math.EC public bool IsValid() { - if (IsInfinity) - return true; - - // TODO Sanity-check the field elements + return ImplIsValid(false, true); + } - ECCurve curve = Curve; - if (curve != null) - { - if (!SatisfiesCurveEquation()) - return false; + internal bool IsValidPartial() + { + return ImplIsValid(false, false); + } - if (!SatisfiesCofactor()) - return false; - } + internal bool ImplIsValid(bool decompressed, bool checkOrder) + { + if (IsInfinity) + return true; - return true; + ValidityCallback callback = new ValidityCallback(this, decompressed, checkOrder); + ValidityPreCompInfo validity = (ValidityPreCompInfo)Curve.Precompute(this, ValidityPreCompInfo.PRECOMP_NAME, callback); + return !validity.HasFailed(); } public virtual ECPoint ScaleX(ECFieldElement scale) @@ -462,6 +444,52 @@ namespace Org.BouncyCastle.Math.EC { return TwicePlus(this); } + + private class ValidityCallback + : IPreCompCallback + { + private readonly ECPoint m_outer; + private readonly bool m_decompressed, m_checkOrder; + + internal ValidityCallback(ECPoint outer, bool decompressed, bool checkOrder) + { + this.m_outer = outer; + this.m_decompressed = decompressed; + this.m_checkOrder = checkOrder; + } + + public PreCompInfo Precompute(PreCompInfo existing) + { + ValidityPreCompInfo info = existing as ValidityPreCompInfo; + if (info == null) + { + info = new ValidityPreCompInfo(); + } + + if (info.HasFailed()) + return info; + + if (!info.HasCurveEquationPassed()) + { + if (!m_decompressed && !m_outer.SatisfiesCurveEquation()) + { + info.ReportFailed(); + return info; + } + info.ReportCurveEquationPassed(); + } + if (m_checkOrder && !info.HasOrderPassed()) + { + if (!m_outer.SatisfiesOrder()) + { + info.ReportFailed(); + return info; + } + info.ReportOrderPassed(); + } + return info; + } + } } public abstract class ECPointBase @@ -608,6 +636,7 @@ namespace Org.BouncyCastle.Math.EC * @param x affine x co-ordinate * @param y affine y co-ordinate */ + [Obsolete("Use ECCurve.CreatePoint to construct points")] public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { @@ -621,6 +650,7 @@ namespace Org.BouncyCastle.Math.EC * @param y affine y co-ordinate * @param withCompression if true encode with point compression */ + [Obsolete("Per-point compression property will be removed, see GetEncoded(bool)")] public FpPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { @@ -635,7 +665,7 @@ namespace Org.BouncyCastle.Math.EC protected override ECPoint Detach() { - return new FpPoint(null, AffineXCoord, AffineYCoord); + return new FpPoint(null, AffineXCoord, AffineYCoord, false); } public override ECFieldElement GetZCoord(int index) @@ -1384,6 +1414,46 @@ namespace Org.BouncyCastle.Math.EC return lhs.Equals(rhs); } + protected override bool SatisfiesOrder() + { + ECCurve curve = Curve; + BigInteger cofactor = curve.Cofactor; + if (BigInteger.Two.Equals(cofactor)) + { + /* + * Check that the trace of (X + A) is 0, then there exists a solution to L^2 + L = X + A, + * and so a halving is possible, so this point is the double of another. + */ + ECPoint N = this.Normalize(); + ECFieldElement X = N.AffineXCoord; + ECFieldElement rhs = X.Add(curve.A); + return ((AbstractF2mFieldElement)rhs).Trace() == 0; + } + if (BigInteger.ValueOf(4).Equals(cofactor)) + { + /* + * Solve L^2 + L = X + A to find the half of this point, if it exists (fail if not). + * Generate both possibilities for the square of the half-point's x-coordinate (w), + * and check if Tr(w + A) == 0 for at least one; then a second halving is possible + * (see comments for cofactor 2 above), so this point is four times another. + * + * Note: Tr(x^2) == Tr(x). + */ + ECPoint N = this.Normalize(); + ECFieldElement X = N.AffineXCoord; + ECFieldElement lambda = ((AbstractF2mCurve)curve).SolveQuadraticEquation(X.Add(curve.A)); + if (lambda == null) + return false; + + ECFieldElement w = X.Multiply(lambda).Add(N.AffineYCoord); + ECFieldElement t = w.Add(curve.A); + return ((AbstractF2mFieldElement)t).Trace() == 0 + || ((AbstractF2mFieldElement)(t.Add(X))).Trace() == 0; + } + + return base.SatisfiesOrder(); + } + public override ECPoint ScaleX(ECFieldElement scale) { if (this.IsInfinity) @@ -1529,6 +1599,7 @@ namespace Org.BouncyCastle.Math.EC * @param x x point * @param y y point */ + [Obsolete("Use ECCurve.CreatePoint to construct points")] public F2mPoint( ECCurve curve, ECFieldElement x, @@ -1543,6 +1614,7 @@ namespace Org.BouncyCastle.Math.EC * @param y y point * @param withCompression true if encode with point compression. */ + [Obsolete("Per-point compression property will be removed, see GetEncoded(bool)")] public F2mPoint( ECCurve curve, ECFieldElement x, @@ -1573,19 +1645,9 @@ namespace Org.BouncyCastle.Math.EC { } - /** - * Constructor for point at infinity - */ - [Obsolete("Use ECCurve.Infinity property")] - public F2mPoint( - ECCurve curve) - : this(curve, null, null) - { - } - protected override ECPoint Detach() { - return new F2mPoint(null, AffineXCoord, AffineYCoord); + return new F2mPoint(null, AffineXCoord, AffineYCoord, false); } public override ECFieldElement YCoord diff --git a/crypto/src/math/ec/custom/djb/Curve25519FieldElement.cs b/crypto/src/math/ec/custom/djb/Curve25519FieldElement.cs index 732e9e468..37256a550 100644 --- a/crypto/src/math/ec/custom/djb/Curve25519FieldElement.cs +++ b/crypto/src/math/ec/custom/djb/Curve25519FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Djb { internal class Curve25519FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = Curve25519.q; diff --git a/crypto/src/math/ec/custom/gm/SM2P256V1FieldElement.cs b/crypto/src/math/ec/custom/gm/SM2P256V1FieldElement.cs index 4f6428f9e..087a040f2 100644 --- a/crypto/src/math/ec/custom/gm/SM2P256V1FieldElement.cs +++ b/crypto/src/math/ec/custom/gm/SM2P256V1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.GM { internal class SM2P256V1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SM2P256V1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP128R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP128R1FieldElement.cs index fa7951d5d..5912a87e8 100644 --- a/crypto/src/math/ec/custom/sec/SecP128R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP128R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP128R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP128R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP160R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP160R1FieldElement.cs index d1fc75644..3ab11bdae 100644 --- a/crypto/src/math/ec/custom/sec/SecP160R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP160R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP160R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP160R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP160R2FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP160R2FieldElement.cs index bdb5245b2..9d8131857 100644 --- a/crypto/src/math/ec/custom/sec/SecP160R2FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP160R2FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP160R2FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP160R2Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP192K1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP192K1FieldElement.cs index dce377035..54b72573c 100644 --- a/crypto/src/math/ec/custom/sec/SecP192K1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP192K1FieldElement.cs @@ -7,7 +7,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP192K1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP192K1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP192R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP192R1FieldElement.cs index 45bcb00f0..f3e12b542 100644 --- a/crypto/src/math/ec/custom/sec/SecP192R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP192R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP192R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP192R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP224K1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP224K1FieldElement.cs index fec07436a..ef53a88d6 100644 --- a/crypto/src/math/ec/custom/sec/SecP224K1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP224K1FieldElement.cs @@ -7,7 +7,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP224K1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP224K1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP224R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP224R1FieldElement.cs index 2b9a06564..5780b7481 100644 --- a/crypto/src/math/ec/custom/sec/SecP224R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP224R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP224R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP224R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP256K1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP256K1FieldElement.cs index 473113d0f..9a604bdb7 100644 --- a/crypto/src/math/ec/custom/sec/SecP256K1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP256K1FieldElement.cs @@ -7,7 +7,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP256K1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP256K1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP256R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP256R1FieldElement.cs index d7838aead..808e99ea6 100644 --- a/crypto/src/math/ec/custom/sec/SecP256R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP256R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP256R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP256R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP384R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP384R1FieldElement.cs index 18d48a57d..7eedccae6 100644 --- a/crypto/src/math/ec/custom/sec/SecP384R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP384R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP384R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP384R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecP521R1FieldElement.cs b/crypto/src/math/ec/custom/sec/SecP521R1FieldElement.cs index 6f02a7eb5..96658a8e5 100644 --- a/crypto/src/math/ec/custom/sec/SecP521R1FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecP521R1FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecP521R1FieldElement - : ECFieldElement + : AbstractFpFieldElement { public static readonly BigInteger Q = SecP521R1Curve.q; diff --git a/crypto/src/math/ec/custom/sec/SecT113FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT113FieldElement.cs index 9ba25d987..bb87b00fc 100644 --- a/crypto/src/math/ec/custom/sec/SecT113FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT113FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT113FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT113FieldElement(z); } + public override int Trace() + { + return (int)SecT113Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat128.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT131FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT131FieldElement.cs index c38e8eb0a..f96c7ca39 100644 --- a/crypto/src/math/ec/custom/sec/SecT131FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT131FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT131FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT131FieldElement(z); } + public override int Trace() + { + return (int)SecT131Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat192.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT163FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT163FieldElement.cs index 07bd07652..903645999 100644 --- a/crypto/src/math/ec/custom/sec/SecT163FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT163FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT163FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT163FieldElement(z); } + public override int Trace() + { + return (int)SecT163Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat192.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT193FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT193FieldElement.cs index d04e68d3f..9813bcb01 100644 --- a/crypto/src/math/ec/custom/sec/SecT193FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT193FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT193FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT193FieldElement(z); } + public override int Trace() + { + return (int)SecT193Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat256.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT233FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT233FieldElement.cs index 64d09bd6d..fbfe35e13 100644 --- a/crypto/src/math/ec/custom/sec/SecT233FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT233FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT233FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT233FieldElement(z); } + public override int Trace() + { + return (int)SecT233Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat256.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT239FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT239FieldElement.cs index 18563f746..b1b58e89b 100644 --- a/crypto/src/math/ec/custom/sec/SecT239FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT239FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT239FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT239FieldElement(z); } + public override int Trace() + { + return (int)SecT239Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat256.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT283FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT283FieldElement.cs index b054bedfb..c1bb2e30c 100644 --- a/crypto/src/math/ec/custom/sec/SecT283FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT283FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT283FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT283FieldElement(z); } + public override int Trace() + { + return (int)SecT283Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat320.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT409FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT409FieldElement.cs index 7076905bb..68a63312d 100644 --- a/crypto/src/math/ec/custom/sec/SecT409FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT409FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT409FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT409FieldElement(z); } + public override int Trace() + { + return (int)SecT409Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat448.Create64(); diff --git a/crypto/src/math/ec/custom/sec/SecT571FieldElement.cs b/crypto/src/math/ec/custom/sec/SecT571FieldElement.cs index 5f28c01be..c9f3aa5c0 100644 --- a/crypto/src/math/ec/custom/sec/SecT571FieldElement.cs +++ b/crypto/src/math/ec/custom/sec/SecT571FieldElement.cs @@ -6,7 +6,7 @@ using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.EC.Custom.Sec { internal class SecT571FieldElement - : ECFieldElement + : AbstractF2mFieldElement { protected internal readonly ulong[] x; @@ -150,6 +150,11 @@ namespace Org.BouncyCastle.Math.EC.Custom.Sec return new SecT571FieldElement(z); } + public override int Trace() + { + return (int)SecT571Field.Trace(x); + } + public override ECFieldElement Invert() { ulong[] z = Nat576.Create64(); diff --git a/crypto/src/math/ec/multiplier/AbstractECMultiplier.cs b/crypto/src/math/ec/multiplier/AbstractECMultiplier.cs index 517881323..c2580c852 100644 --- a/crypto/src/math/ec/multiplier/AbstractECMultiplier.cs +++ b/crypto/src/math/ec/multiplier/AbstractECMultiplier.cs @@ -16,9 +16,14 @@ * Although the various multipliers ought not to produce invalid output under normal * circumstances, a final check here is advised to guard against fault attacks. */ - return ECAlgorithms.ValidatePoint(result); + return CheckResult(result); } protected abstract ECPoint MultiplyPositive(ECPoint p, BigInteger k); + + protected virtual ECPoint CheckResult(ECPoint p) + { + return ECAlgorithms.ImplCheckResult(p); + } } } diff --git a/crypto/src/math/ec/multiplier/FixedPointCombMultiplier.cs b/crypto/src/math/ec/multiplier/FixedPointCombMultiplier.cs index adaedb809..505832442 100644 --- a/crypto/src/math/ec/multiplier/FixedPointCombMultiplier.cs +++ b/crypto/src/math/ec/multiplier/FixedPointCombMultiplier.cs @@ -52,11 +52,5 @@ namespace Org.BouncyCastle.Math.EC.Multiplier return R.Add(info.Offset); } - - [Obsolete("Is no longer used; remove any overrides in subclasses.")] - protected virtual int GetWidthForCombSize(int combSize) - { - return combSize > 257 ? 6 : 5; - } } } diff --git a/crypto/src/math/ec/multiplier/FixedPointPreCompInfo.cs b/crypto/src/math/ec/multiplier/FixedPointPreCompInfo.cs index 4c0b404df..5d6af9e5d 100644 --- a/crypto/src/math/ec/multiplier/FixedPointPreCompInfo.cs +++ b/crypto/src/math/ec/multiplier/FixedPointPreCompInfo.cs @@ -11,13 +11,6 @@ namespace Org.BouncyCastle.Math.EC.Multiplier protected ECPoint m_offset = null; /** - * Array holding the precomputed <code>ECPoint</code>s used for a fixed - * point multiplication. - */ - [Obsolete("Will be removed")] - protected ECPoint[] m_preComp = null; - - /** * Lookup table for the precomputed <code>ECPoint</code>s used for a fixed point multiplication. */ protected ECLookupTable m_lookupTable = null; @@ -41,13 +34,6 @@ namespace Org.BouncyCastle.Math.EC.Multiplier set { this.m_offset = value; } } - [Obsolete("Use 'LookupTable' property instead.")] - public virtual ECPoint[] PreComp - { - get { return m_preComp; } - set { this.m_preComp = value; } - } - public virtual int Width { get { return m_width; } diff --git a/crypto/src/math/ec/multiplier/FixedPointUtilities.cs b/crypto/src/math/ec/multiplier/FixedPointUtilities.cs index cc7203314..88f178e24 100644 --- a/crypto/src/math/ec/multiplier/FixedPointUtilities.cs +++ b/crypto/src/math/ec/multiplier/FixedPointUtilities.cs @@ -14,36 +14,40 @@ namespace Org.BouncyCastle.Math.EC.Multiplier public static FixedPointPreCompInfo GetFixedPointPreCompInfo(PreCompInfo preCompInfo) { - if ((preCompInfo != null) && (preCompInfo is FixedPointPreCompInfo)) - { - return (FixedPointPreCompInfo)preCompInfo; - } - - return new FixedPointPreCompInfo(); + return preCompInfo as FixedPointPreCompInfo; } - [Obsolete("Use 'Precompute(ECPoint)' instead, as minWidth parameter is now ignored")] - public static FixedPointPreCompInfo Precompute(ECPoint p, int minWidth) + public static FixedPointPreCompInfo Precompute(ECPoint p) { - return Precompute(p); + return (FixedPointPreCompInfo)p.Curve.Precompute(p, PRECOMP_NAME, new FixedPointCallback(p)); } - public static FixedPointPreCompInfo Precompute(ECPoint p) + private class FixedPointCallback + : IPreCompCallback { - ECCurve c = p.Curve; - int minWidth = GetCombSize(c) > 257 ? 6 : 5; + private readonly ECPoint m_p; - int n = 1 << minWidth; - FixedPointPreCompInfo info = GetFixedPointPreCompInfo(c.GetPreCompInfo(p, PRECOMP_NAME)); - ECPoint[] lookupTable = info.PreComp; + internal FixedPointCallback(ECPoint p) + { + this.m_p = p; + } - if (lookupTable == null || lookupTable.Length < n) + public PreCompInfo Precompute(PreCompInfo existing) { - int bits = GetCombSize(c); + FixedPointPreCompInfo existingFP = (existing is FixedPointPreCompInfo) ? (FixedPointPreCompInfo)existing : null; + + ECCurve c = m_p.Curve; + int bits = FixedPointUtilities.GetCombSize(c); + int minWidth = bits > 250 ? 6 : 5; + int n = 1 << minWidth; + + if (CheckExisting(existingFP, n)) + return existingFP; + int d = (bits + minWidth - 1) / minWidth; ECPoint[] pow2Table = new ECPoint[minWidth + 1]; - pow2Table[0] = p; + pow2Table[0] = m_p; for (int i = 1; i < minWidth; ++i) { pow2Table[i] = pow2Table[i - 1].TimesPow2(d); @@ -53,8 +57,8 @@ namespace Org.BouncyCastle.Math.EC.Multiplier pow2Table[minWidth] = pow2Table[0].Subtract(pow2Table[1]); c.NormalizeAll(pow2Table); - - lookupTable = new ECPoint[n]; + + ECPoint[] lookupTable = new ECPoint[n]; lookupTable[0] = pow2Table[0]; for (int bit = minWidth - 1; bit >= 0; --bit) @@ -70,15 +74,22 @@ namespace Org.BouncyCastle.Math.EC.Multiplier c.NormalizeAll(lookupTable); - info.LookupTable = c.CreateCacheSafeLookupTable(lookupTable, 0, lookupTable.Length); - info.Offset = pow2Table[minWidth]; - info.PreComp = lookupTable; - info.Width = minWidth; + FixedPointPreCompInfo result = new FixedPointPreCompInfo(); + result.LookupTable = c.CreateCacheSafeLookupTable(lookupTable, 0, lookupTable.Length); + result.Offset = pow2Table[minWidth]; + result.Width = minWidth; + return result; + } - c.SetPreCompInfo(p, PRECOMP_NAME, info); + private bool CheckExisting(FixedPointPreCompInfo existingFP, int n) + { + return existingFP != null && CheckTable(existingFP.LookupTable, n); } - return info; + private bool CheckTable(ECLookupTable table, int n) + { + return table != null && table.Size >= n; + } } } } diff --git a/crypto/src/math/ec/multiplier/IPreCompCallback.cs b/crypto/src/math/ec/multiplier/IPreCompCallback.cs new file mode 100644 index 000000000..e64ae834d --- /dev/null +++ b/crypto/src/math/ec/multiplier/IPreCompCallback.cs @@ -0,0 +1,9 @@ +using System; + +namespace Org.BouncyCastle.Math.EC.Multiplier +{ + public interface IPreCompCallback + { + PreCompInfo Precompute(PreCompInfo existing); + } +} diff --git a/crypto/src/math/ec/multiplier/ValidityPreCompInfo.cs b/crypto/src/math/ec/multiplier/ValidityPreCompInfo.cs new file mode 100644 index 000000000..7ec2cbb95 --- /dev/null +++ b/crypto/src/math/ec/multiplier/ValidityPreCompInfo.cs @@ -0,0 +1,44 @@ +using System; + +namespace Org.BouncyCastle.Math.EC.Multiplier +{ + internal class ValidityPreCompInfo + : PreCompInfo + { + internal static readonly string PRECOMP_NAME = "bc_validity"; + + private bool failed = false; + private bool curveEquationPassed = false; + private bool orderPassed = false; + + internal bool HasFailed() + { + return failed; + } + + internal void ReportFailed() + { + failed = true; + } + + internal bool HasCurveEquationPassed() + { + return curveEquationPassed; + } + + internal void ReportCurveEquationPassed() + { + curveEquationPassed = true; + } + + internal bool HasOrderPassed() + { + return orderPassed; + } + + internal void ReportOrderPassed() + { + orderPassed = true; + } + } +} diff --git a/crypto/src/math/ec/multiplier/WNafUtilities.cs b/crypto/src/math/ec/multiplier/WNafUtilities.cs index 7d565dfbd..e893abd49 100644 --- a/crypto/src/math/ec/multiplier/WNafUtilities.cs +++ b/crypto/src/math/ec/multiplier/WNafUtilities.cs @@ -287,12 +287,7 @@ namespace Org.BouncyCastle.Math.EC.Multiplier public static WNafPreCompInfo GetWNafPreCompInfo(PreCompInfo preCompInfo) { - if ((preCompInfo != null) && (preCompInfo is WNafPreCompInfo)) - { - return (WNafPreCompInfo)preCompInfo; - } - - return new WNafPreCompInfo(); + return preCompInfo as WNafPreCompInfo; } /** @@ -333,106 +328,178 @@ namespace Org.BouncyCastle.Math.EC.Multiplier WNafPreCompInfo wnafPreCompP = Precompute(p, width, includeNegated); ECPoint q = pointMap.Map(p); - WNafPreCompInfo wnafPreCompQ = GetWNafPreCompInfo(c.GetPreCompInfo(q, PRECOMP_NAME)); + c.Precompute(q, PRECOMP_NAME, new MapPointCallback(wnafPreCompP, includeNegated, pointMap)); + return q; + } - ECPoint twiceP = wnafPreCompP.Twice; - if (twiceP != null) - { - ECPoint twiceQ = pointMap.Map(twiceP); - wnafPreCompQ.Twice = twiceQ; - } + public static WNafPreCompInfo Precompute(ECPoint p, int width, bool includeNegated) + { + return (WNafPreCompInfo)p.Curve.Precompute(p, PRECOMP_NAME, new WNafCallback(p, width, includeNegated)); + } + + private static byte[] Trim(byte[] a, int length) + { + byte[] result = new byte[length]; + Array.Copy(a, 0, result, 0, result.Length); + return result; + } + + private static int[] Trim(int[] a, int length) + { + int[] result = new int[length]; + Array.Copy(a, 0, result, 0, result.Length); + return result; + } + + private static ECPoint[] ResizeTable(ECPoint[] a, int length) + { + ECPoint[] result = new ECPoint[length]; + Array.Copy(a, 0, result, 0, a.Length); + return result; + } + + private class MapPointCallback + : IPreCompCallback + { + private readonly WNafPreCompInfo m_wnafPreCompP; + private readonly bool m_includeNegated; + private readonly ECPointMap m_pointMap; - ECPoint[] preCompP = wnafPreCompP.PreComp; - ECPoint[] preCompQ = new ECPoint[preCompP.Length]; - for (int i = 0; i < preCompP.Length; ++i) + internal MapPointCallback(WNafPreCompInfo wnafPreCompP, bool includeNegated, ECPointMap pointMap) { - preCompQ[i] = pointMap.Map(preCompP[i]); + this.m_wnafPreCompP = wnafPreCompP; + this.m_includeNegated = includeNegated; + this.m_pointMap = pointMap; } - wnafPreCompQ.PreComp = preCompQ; - if (includeNegated) + public PreCompInfo Precompute(PreCompInfo existing) { - ECPoint[] preCompNegQ = new ECPoint[preCompQ.Length]; - for (int i = 0; i < preCompNegQ.Length; ++i) + WNafPreCompInfo result = new WNafPreCompInfo(); + + ECPoint twiceP = m_wnafPreCompP.Twice; + if (twiceP != null) { - preCompNegQ[i] = preCompQ[i].Negate(); + ECPoint twiceQ = m_pointMap.Map(twiceP); + result.Twice = twiceQ; } - wnafPreCompQ.PreCompNeg = preCompNegQ; - } - c.SetPreCompInfo(q, PRECOMP_NAME, wnafPreCompQ); + ECPoint[] preCompP = m_wnafPreCompP.PreComp; + ECPoint[] preCompQ = new ECPoint[preCompP.Length]; + for (int i = 0; i < preCompP.Length; ++i) + { + preCompQ[i] = m_pointMap.Map(preCompP[i]); + } + result.PreComp = preCompQ; - return q; + if (m_includeNegated) + { + ECPoint[] preCompNegQ = new ECPoint[preCompQ.Length]; + for (int i = 0; i < preCompNegQ.Length; ++i) + { + preCompNegQ[i] = preCompQ[i].Negate(); + } + result.PreCompNeg = preCompNegQ; + } + + return result; + } } - public static WNafPreCompInfo Precompute(ECPoint p, int width, bool includeNegated) + private class WNafCallback + : IPreCompCallback { - ECCurve c = p.Curve; - WNafPreCompInfo wnafPreCompInfo = GetWNafPreCompInfo(c.GetPreCompInfo(p, PRECOMP_NAME)); + private readonly ECPoint m_p; + private readonly int m_width; + private readonly bool m_includeNegated; - int iniPreCompLen = 0, reqPreCompLen = 1 << System.Math.Max(0, width - 2); - - ECPoint[] preComp = wnafPreCompInfo.PreComp; - if (preComp == null) + internal WNafCallback(ECPoint p, int width, bool includeNegated) { - preComp = EMPTY_POINTS; - } - else - { - iniPreCompLen = preComp.Length; + this.m_p = p; + this.m_width = width; + this.m_includeNegated = includeNegated; } - if (iniPreCompLen < reqPreCompLen) + public PreCompInfo Precompute(PreCompInfo existing) { - preComp = ResizeTable(preComp, reqPreCompLen); + WNafPreCompInfo existingWNaf = existing as WNafPreCompInfo; + + int reqPreCompLen = 1 << System.Math.Max(0, m_width - 2); + + if (CheckExisting(existingWNaf, reqPreCompLen, m_includeNegated)) + return existingWNaf; - if (reqPreCompLen == 1) + ECCurve c = m_p.Curve; + ECPoint[] preComp = null, preCompNeg = null; + ECPoint twiceP = null; + + if (existingWNaf != null) + { + preComp = existingWNaf.PreComp; + preCompNeg = existingWNaf.PreCompNeg; + twiceP = existingWNaf.Twice; + } + + int iniPreCompLen = 0; + if (preComp == null) { - preComp[0] = p.Normalize(); + preComp = EMPTY_POINTS; } else { - int curPreCompLen = iniPreCompLen; - if (curPreCompLen == 0) - { - preComp[0] = p; - curPreCompLen = 1; - } + iniPreCompLen = preComp.Length; + } - ECFieldElement iso = null; + if (iniPreCompLen < reqPreCompLen) + { + preComp = WNafUtilities.ResizeTable(preComp, reqPreCompLen); - if (reqPreCompLen == 2) + if (reqPreCompLen == 1) { - preComp[1] = p.ThreeTimes(); + preComp[0] = m_p.Normalize(); } else { - ECPoint twiceP = wnafPreCompInfo.Twice, last = preComp[curPreCompLen - 1]; - if (twiceP == null) + int curPreCompLen = iniPreCompLen; + if (curPreCompLen == 0) + { + preComp[0] = m_p; + curPreCompLen = 1; + } + + ECFieldElement iso = null; + + if (reqPreCompLen == 2) + { + preComp[1] = m_p.ThreeTimes(); + } + else { - twiceP = preComp[0].Twice(); - wnafPreCompInfo.Twice = twiceP; - - /* - * For Fp curves with Jacobian projective coordinates, use a (quasi-)isomorphism - * where 'twiceP' is "affine", so that the subsequent additions are cheaper. This - * also requires scaling the initial point's X, Y coordinates, and reversing the - * isomorphism as part of the subsequent normalization. - * - * NOTE: The correctness of this optimization depends on: - * 1) additions do not use the curve's A, B coefficients. - * 2) no special cases (i.e. Q +/- Q) when calculating 1P, 3P, 5P, ... - */ - if (!twiceP.IsInfinity && ECAlgorithms.IsFpCurve(c) && c.FieldSize >= 64) + ECPoint isoTwiceP = twiceP, last = preComp[curPreCompLen - 1]; + if (isoTwiceP == null) { - switch (c.CoordinateSystem) + isoTwiceP = preComp[0].Twice(); + twiceP = isoTwiceP; + + /* + * For Fp curves with Jacobian projective coordinates, use a (quasi-)isomorphism + * where 'twiceP' is "affine", so that the subsequent additions are cheaper. This + * also requires scaling the initial point's X, Y coordinates, and reversing the + * isomorphism as part of the subsequent normalization. + * + * NOTE: The correctness of this optimization depends on: + * 1) additions do not use the curve's A, B coefficients. + * 2) no special cases (i.e. Q +/- Q) when calculating 1P, 3P, 5P, ... + */ + if (!twiceP.IsInfinity && ECAlgorithms.IsFpCurve(c) && c.FieldSize >= 64) { + switch (c.CoordinateSystem) + { case ECCurve.COORD_JACOBIAN: case ECCurve.COORD_JACOBIAN_CHUDNOVSKY: case ECCurve.COORD_JACOBIAN_MODIFIED: { iso = twiceP.GetZCoord(0); - twiceP = c.CreatePoint(twiceP.XCoord.ToBigInteger(), + isoTwiceP = c.CreatePoint(twiceP.XCoord.ToBigInteger(), twiceP.YCoord.ToBigInteger()); ECFieldElement iso2 = iso.Square(), iso3 = iso2.Multiply(iso); @@ -444,81 +511,69 @@ namespace Org.BouncyCastle.Math.EC.Multiplier } break; } + } } } - } - while (curPreCompLen < reqPreCompLen) - { - /* - * Compute the new ECPoints for the precomputation array. The values 1, 3, - * 5, ..., 2^(width-1)-1 times p are computed - */ - preComp[curPreCompLen++] = last = last.Add(twiceP); + while (curPreCompLen < reqPreCompLen) + { + /* + * Compute the new ECPoints for the precomputation array. The values 1, 3, + * 5, ..., 2^(width-1)-1 times p are computed + */ + preComp[curPreCompLen++] = last = last.Add(isoTwiceP); + } } - } - /* - * Having oft-used operands in affine form makes operations faster. - */ - c.NormalizeAll(preComp, iniPreCompLen, reqPreCompLen - iniPreCompLen, iso); + /* + * Having oft-used operands in affine form makes operations faster. + */ + c.NormalizeAll(preComp, iniPreCompLen, reqPreCompLen - iniPreCompLen, iso); + } } - } - - wnafPreCompInfo.PreComp = preComp; - - if (includeNegated) - { - ECPoint[] preCompNeg = wnafPreCompInfo.PreCompNeg; - int pos; - if (preCompNeg == null) - { - pos = 0; - preCompNeg = new ECPoint[reqPreCompLen]; - } - else + if (m_includeNegated) { - pos = preCompNeg.Length; - if (pos < reqPreCompLen) + int pos; + if (preCompNeg == null) { - preCompNeg = ResizeTable(preCompNeg, reqPreCompLen); + pos = 0; + preCompNeg = new ECPoint[reqPreCompLen]; + } + else + { + pos = preCompNeg.Length; + if (pos < reqPreCompLen) + { + preCompNeg = WNafUtilities.ResizeTable(preCompNeg, reqPreCompLen); + } } - } - while (pos < reqPreCompLen) - { - preCompNeg[pos] = preComp[pos].Negate(); - ++pos; + while (pos < reqPreCompLen) + { + preCompNeg[pos] = preComp[pos].Negate(); + ++pos; + } } - wnafPreCompInfo.PreCompNeg = preCompNeg; + WNafPreCompInfo result = new WNafPreCompInfo(); + result.PreComp = preComp; + result.PreCompNeg = preCompNeg; + result.Twice = twiceP; + return result; } - c.SetPreCompInfo(p, PRECOMP_NAME, wnafPreCompInfo); - - return wnafPreCompInfo; - } - - private static byte[] Trim(byte[] a, int length) - { - byte[] result = new byte[length]; - Array.Copy(a, 0, result, 0, result.Length); - return result; - } - - private static int[] Trim(int[] a, int length) - { - int[] result = new int[length]; - Array.Copy(a, 0, result, 0, result.Length); - return result; - } + private bool CheckExisting(WNafPreCompInfo existingWNaf, int reqPreCompLen, bool includeNegated) + { + return existingWNaf != null + && CheckTable(existingWNaf.PreComp, reqPreCompLen) + && (!includeNegated || CheckTable(existingWNaf.PreCompNeg, reqPreCompLen)); + } - private static ECPoint[] ResizeTable(ECPoint[] a, int length) - { - ECPoint[] result = new ECPoint[length]; - Array.Copy(a, 0, result, 0, a.Length); - return result; + private bool CheckTable(ECPoint[] table, int reqLen) + { + return table != null && table.Length >= reqLen; + } } } } diff --git a/crypto/src/math/ec/multiplier/WTauNafMultiplier.cs b/crypto/src/math/ec/multiplier/WTauNafMultiplier.cs index 1e7ddae91..4dce54440 100644 --- a/crypto/src/math/ec/multiplier/WTauNafMultiplier.cs +++ b/crypto/src/math/ec/multiplier/WTauNafMultiplier.cs @@ -36,7 +36,7 @@ namespace Org.BouncyCastle.Math.EC.Multiplier ZTauElement rho = Tnaf.PartModReduction(k, m, a, s, mu, (sbyte)10); - return MultiplyWTnaf(p, rho, curve.GetPreCompInfo(p, PRECOMP_NAME), a, mu); + return MultiplyWTnaf(p, rho, a, mu); } /** @@ -50,7 +50,7 @@ namespace Org.BouncyCastle.Math.EC.Multiplier * @return <code>p</code> multiplied by <code>λ</code>. */ private AbstractF2mPoint MultiplyWTnaf(AbstractF2mPoint p, ZTauElement lambda, - PreCompInfo preCompInfo, sbyte a, sbyte mu) + sbyte a, sbyte mu) { ZTauElement[] alpha = (a == 0) ? Tnaf.Alpha0 : Tnaf.Alpha1; @@ -59,7 +59,7 @@ namespace Org.BouncyCastle.Math.EC.Multiplier sbyte[]u = Tnaf.TauAdicWNaf(mu, lambda, Tnaf.Width, BigInteger.ValueOf(Tnaf.Pow2Width), tw, alpha); - return MultiplyFromWTnaf(p, u, preCompInfo); + return MultiplyFromWTnaf(p, u); } /** @@ -71,24 +71,14 @@ namespace Org.BouncyCastle.Math.EC.Multiplier * @param u The the WTNAF of <code>λ</code>.. * @return <code>λ * p</code> */ - private static AbstractF2mPoint MultiplyFromWTnaf(AbstractF2mPoint p, sbyte[] u, PreCompInfo preCompInfo) + private static AbstractF2mPoint MultiplyFromWTnaf(AbstractF2mPoint p, sbyte[] u) { AbstractF2mCurve curve = (AbstractF2mCurve)p.Curve; sbyte a = (sbyte)curve.A.ToBigInteger().IntValue; - AbstractF2mPoint[] pu; - if ((preCompInfo == null) || !(preCompInfo is WTauNafPreCompInfo)) - { - pu = Tnaf.GetPreComp(p, a); - - WTauNafPreCompInfo pre = new WTauNafPreCompInfo(); - pre.PreComp = pu; - curve.SetPreCompInfo(p, PRECOMP_NAME, pre); - } - else - { - pu = ((WTauNafPreCompInfo)preCompInfo).PreComp; - } + WTauNafCallback callback = new WTauNafCallback(p, a); + WTauNafPreCompInfo preCompInfo = (WTauNafPreCompInfo)curve.Precompute(p, PRECOMP_NAME, callback); + AbstractF2mPoint[] pu = preCompInfo.PreComp; // TODO Include negations in precomp (optionally) and use from here AbstractF2mPoint[] puNeg = new AbstractF2mPoint[pu.Length]; @@ -121,5 +111,28 @@ namespace Org.BouncyCastle.Math.EC.Multiplier } return q; } + + private class WTauNafCallback + : IPreCompCallback + { + private readonly AbstractF2mPoint m_p; + private readonly sbyte m_a; + + internal WTauNafCallback(AbstractF2mPoint p, sbyte a) + { + this.m_p = p; + this.m_a = a; + } + + public PreCompInfo Precompute(PreCompInfo existing) + { + if (existing is WTauNafPreCompInfo) + return existing; + + WTauNafPreCompInfo result = new WTauNafPreCompInfo(); + result.PreComp = Tnaf.GetPreComp(m_p, m_a); + return result; + } + } } } diff --git a/crypto/src/math/ec/rfc7748/X25519.cs b/crypto/src/math/ec/rfc7748/X25519.cs index 8c52a21ac..38bc9c1f1 100644 --- a/crypto/src/math/ec/rfc7748/X25519.cs +++ b/crypto/src/math/ec/rfc7748/X25519.cs @@ -10,10 +10,10 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 private const int C_A24 = (C_A + 2)/4; // 0x1 - //private static readonly int[] S_x = new int[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + //private static readonly int[] S_x = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 0x215132111D8354CB52385F46DCA2B71D440F6A51EB4D1207816B1E0137D48290 - private static readonly int[] PsubS_x = new int[]{ 0x03D48290, 0x02C7804D, 0x01207816, 0x028F5A68, 0x00881ED4, 0x00A2B71D, + private static readonly int[] PsubS_x = { 0x03D48290, 0x02C7804D, 0x01207816, 0x028F5A68, 0x00881ED4, 0x00A2B71D, 0x0217D1B7, 0x014CB523, 0x0088EC1A, 0x0042A264 }; private static int[] precompBase = null; diff --git a/crypto/src/math/ec/rfc7748/X25519Field.cs b/crypto/src/math/ec/rfc7748/X25519Field.cs index 282f41628..fd5599657 100644 --- a/crypto/src/math/ec/rfc7748/X25519Field.cs +++ b/crypto/src/math/ec/rfc7748/X25519Field.cs @@ -11,6 +11,9 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 private const int M25 = 0x01FFFFFF; private const int M26 = 0x03FFFFFF; + private static readonly int[] RootNegOne = { 0x020EA0B0, 0x0386C9D2, 0x00478C4E, 0x0035697F, 0x005E8630, + 0x01FBD7A7, 0x0340264F, 0x01F0B2B4, 0x00027E0E, 0x00570649 }; + private X25519Field() {} public static void Add(int[] x, int[] y, int[] z) @@ -21,6 +24,16 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 } } + public static void AddOne(int[] z) + { + z[0] += 1; + } + + public static void AddOne(int[] z, int zOff) + { + z[zOff] += 1; + } + public static void Apm(int[] x, int[] y, int[] zp, int[] zm) { for (int i = 0; i < Size; ++i) @@ -54,6 +67,17 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 z[5] = z5; z[6] = z6; z[7] = z7; z[8] = z8; z[9] = z9; } + public static void CNegate(int negate, int[] z) + { + Debug.Assert(negate >> 1 == 0); + + int mask = 0 - negate; + for (int i = 0; i < Size; ++i) + { + z[i] = (z[i] ^ mask) - mask; + } + } + public static void Copy(int[] x, int xOff, int[] z, int zOff) { for (int i = 0; i < Size; ++i) @@ -67,6 +91,11 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 return new int[Size]; } + public static int[] CreateTable(int n) + { + return new int[Size * n]; + } + public static void CSwap(int swap, int[] a, int[] b) { Debug.Assert(swap >> 1 == 0); @@ -143,24 +172,23 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 // (250 1s) (1 0s) (1 1s) (1 0s) (2 1s) // Addition chain: [1] [2] 3 5 10 15 25 50 75 125 [250] - int[] x2 = Create(); Sqr(x, x2); Mul(x, x2, x2); - int[] x3 = Create(); Sqr(x2, x3); Mul(x, x3, x3); - int[] x5 = x3; Sqr(x3, 2, x5); Mul(x2, x5, x5); - int[] x10 = Create(); Sqr(x5, 5, x10); Mul(x5, x10, x10); - int[] x15 = Create(); Sqr(x10, 5, x15); Mul(x5, x15, x15); - int[] x25 = x5; Sqr(x15, 10, x25); Mul(x10, x25, x25); - int[] x50 = x10; Sqr(x25, 25, x50); Mul(x25, x50, x50); - int[] x75 = x15; Sqr(x50, 25, x75); Mul(x25, x75, x75); - int[] x125 = x25; Sqr(x75, 50, x125); Mul(x50, x125, x125); - int[] x250 = x50; Sqr(x125, 125, x250); Mul(x125, x250, x250); - - int[] t = x125; - Sqr(x250, 2, t); - Mul(t, x, t); + int[] x2 = Create(); + int[] t = Create(); + PowPm5d8(x, x2, t); Sqr(t, 3, t); Mul(t, x2, z); } + public static bool IsZeroVar(int[] x) + { + int d = 0; + for (int i = 0; i < Size; ++i) + { + d |= x[i]; + } + return d == 0; + } + public static void Mul(int[] x, int y, int[] z) { int x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4]; @@ -345,6 +373,14 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 z[9] = z9 + (int)t; } + public static void Negate(int[] x, int[] z) + { + for (int i = 0; i < Size; ++i) + { + z[i] = -x[i]; + } + } + public static void Normalize(int[] z) { int x = (z[9] >> 23) & 1; @@ -353,6 +389,37 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 Debug.Assert(z[9] >> 24 == 0); } + public static void One(int[] z) + { + z[0] = 1; + for (int i = 1; i < Size; ++i) + { + z[i] = 0; + } + } + + private static void PowPm5d8(int[] x, int[] rx2, int[] rz) + { + // z = x^((p-5)/8) = x^FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD + // (250 1s) (1 0s) (1 1s) + // Addition chain: [1] 2 3 5 10 15 25 50 75 125 [250] + + int[] x2 = rx2; Sqr(x, x2); Mul(x, x2, x2); + int[] x3 = Create(); Sqr(x2, x3); Mul(x, x3, x3); + int[] x5 = x3; Sqr(x3, 2, x5); Mul(x2, x5, x5); + int[] x10 = Create(); Sqr(x5, 5, x10); Mul(x5, x10, x10); + int[] x15 = Create(); Sqr(x10, 5, x15); Mul(x5, x15, x15); + int[] x25 = x5; Sqr(x15, 10, x25); Mul(x10, x25, x25); + int[] x50 = x10; Sqr(x25, 25, x50); Mul(x25, x50, x50); + int[] x75 = x15; Sqr(x50, 25, x75); Mul(x25, x75, x75); + int[] x125 = x25; Sqr(x75, 50, x125); Mul(x50, x125, x125); + int[] x250 = x50; Sqr(x125, 125, x250); Mul(x125, x250, x250); + + int[] t = x125; + Sqr(x250, 2, t); + Mul(t, x, rz); + } + private static void Reduce(int[] z, int c) { int z9 = z[9], t = z9; @@ -509,6 +576,45 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 } } + public static bool SqrtRatioVar(int[] u, int[] v, int[] z) + { + int[] uv3 = Create(); + int[] uv7 = Create(); + + Mul(u, v, uv3); + Sqr(v, uv7); + Mul(uv3, uv7, uv3); + Sqr(uv7, uv7); + Mul(uv7, uv3, uv7); + + int[] t = Create(); + int[] x = Create(); + PowPm5d8(uv7, t, x); + Mul(x, uv3, x); + + int[] vx2 = Create(); + Sqr(x, vx2); + Mul(vx2, v, vx2); + + Sub(vx2, u, t); + Normalize(t); + if (IsZeroVar(t)) + { + Copy(x, 0, z, 0); + return true; + } + + Add(vx2, u, t); + Normalize(t); + if (IsZeroVar(t)) + { + Mul(x, RootNegOne, z); + return true; + } + + return false; + } + public static void Sub(int[] x, int[] y, int[] z) { for (int i = 0; i < Size; ++i) @@ -516,5 +622,18 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 z[i] = x[i] - y[i]; } } + + public static void SubOne(int[] z) + { + z[0] -= 1; + } + + public static void Zero(int[] z) + { + for (int i = 0; i < Size; ++i) + { + z[i] = 0; + } + } } } diff --git a/crypto/src/math/ec/rfc7748/X448.cs b/crypto/src/math/ec/rfc7748/X448.cs index 8ded25a06..4e6e32879 100644 --- a/crypto/src/math/ec/rfc7748/X448.cs +++ b/crypto/src/math/ec/rfc7748/X448.cs @@ -10,14 +10,14 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 private const uint C_A24 = (C_A + 2)/4; // 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE - private static readonly uint[] S_x = new uint[]{ 0x0FFFFFFEU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, + private static readonly uint[] S_x = { 0x0FFFFFFEU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFEU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU, 0x0FFFFFFFU }; // 0xF0FAB725013244423ACF03881AFFEB7BDACDD1031C81B9672954459D84C1F823F1BD65643ACE1B5123AC33FF1C69BAF8ACB1197DC99D2720 - private static readonly uint[] PsubS_x = new uint[]{ 0x099d2720U, 0x0b1197dcU, 0x09baf8acU, 0x033ff1c6U, 0x0b5123acU, - 0x0643ace1U, 0x03f1bd65U, 0x084c1f82U, 0x0954459dU, 0x081b9672U, 0x0dd1031cU, 0x0eb7bdacU, 0x03881affU, 0x0423acf0U, - 0x05013244U, 0x0f0fab72U }; + private static readonly uint[] PsubS_x = { 0x099D2720U, 0x0B1197DCU, 0x09BAF8ACU, 0x033FF1C6U, 0x0B5123ACU, + 0x0643ACE1U, 0x03F1BD65U, 0x084C1F82U, 0x0954459DU, 0x081B9672U, 0x0DD1031CU, 0x0EB7BDACU, 0x03881AFFU, 0x0423ACF0U, + 0x05013244U, 0x0F0FAB72U }; private static uint[] precompBase = null; diff --git a/crypto/src/math/ec/rfc7748/X448Field.cs b/crypto/src/math/ec/rfc7748/X448Field.cs index 0c44f1eb5..5a682714d 100644 --- a/crypto/src/math/ec/rfc7748/X448Field.cs +++ b/crypto/src/math/ec/rfc7748/X448Field.cs @@ -1,6 +1,8 @@ using System; using System.Diagnostics; +using Org.BouncyCastle.Math.Raw; + namespace Org.BouncyCastle.Math.EC.Rfc7748 { [CLSCompliantAttribute(false)] @@ -20,6 +22,16 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 } } + public static void AddOne(uint[] z) + { + z[0] += 1; + } + + public static void AddOne(uint[] z, int zOff) + { + z[zOff] += 1; + } + //public static void Apm(int[] x, int[] y, int[] zp, int[] zm) //{ // for (int i = 0; i < Size; ++i) @@ -62,6 +74,16 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 z[8] = z8; z[9] = z9; z[10] = z10; z[11] = z11; z[12] = z12; z[13] = z13; z[14] = z14; z[15] = z15; } + public static void CNegate(int negate, uint[] z) + { + Debug.Assert(negate >> 1 == 0); + + uint[] t = Create(); + Sub(t, z, t); + + Nat.CMov(Size, negate, t, 0, z, 0); + } + public static void Copy(uint[] x, int xOff, uint[] z, int zOff) { for (int i = 0; i < Size; ++i) @@ -166,25 +188,23 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 // z = x^(p-2) = x^(2^448 - 2^224 - 3) // (223 1s) (1 0s) (222 1s) (1 0s) (1 1s) // Addition chain: [1] 2 3 6 9 18 19 37 74 111 [222] [223] - uint[] x2 = Create(); Sqr(x, x2); Mul(x, x2, x2); - uint[] x3 = Create(); Sqr(x2, x3); Mul(x, x3, x3); - uint[] x6 = Create(); Sqr(x3, 3, x6); Mul(x3, x6, x6); - uint[] x9 = Create(); Sqr(x6, 3, x9); Mul(x3, x9, x9); - uint[] x18 = Create(); Sqr(x9, 9, x18); Mul(x9, x18, x18); - uint[] x19 = Create(); Sqr(x18, x19); Mul(x, x19, x19); - uint[] x37 = Create(); Sqr(x19, 18, x37); Mul(x18, x37, x37); - uint[] x74 = Create(); Sqr(x37, 37, x74); Mul(x37, x74, x74); - uint[] x111 = Create(); Sqr(x74, 37, x111); Mul(x37, x111, x111); - uint[] x222 = Create(); Sqr(x111, 111, x222); Mul(x111, x222, x222); - uint[] x223 = Create(); Sqr(x222, x223); Mul(x, x223, x223); uint[] t = Create(); - Sqr(x223, 223, t); - Mul(t, x222, t); + PowPm3d4(x, t); Sqr(t, 2, t); Mul(t, x, z); } + public static bool IsZeroVar(uint[] x) + { + uint d = 0; + for (int i = 0; i < Size; ++i) + { + d |= x[i]; + } + return d == 0U; + } + public static void Mul(uint[] x, uint y, uint[] z) { uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7]; @@ -563,6 +583,12 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 z[15] = z15; } + public static void Negate(uint[] x, uint[] z) + { + uint[] zero = Create(); + Sub(zero, x, z); + } + public static void Normalize(uint[] z) { //int x = (z[15] >> (28 - 1)) & 1; @@ -571,6 +597,37 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 Debug.Assert(z[15] >> 28 == 0U); } + public static void One(uint[] z) + { + z[0] = 1U; + for (int i = 1; i < Size; ++i) + { + z[i] = 0; + } + } + + private static void PowPm3d4(uint[] x, uint[] z) + { + // z = x^((p-3)/4) = x^(2^446 - 2^222 - 1) + // (223 1s) (1 0s) (222 1s) + // Addition chain: 1 2 3 6 9 18 19 37 74 111 [222] [223] + uint[] x2 = Create(); Sqr(x, x2); Mul(x, x2, x2); + uint[] x3 = Create(); Sqr(x2, x3); Mul(x, x3, x3); + uint[] x6 = Create(); Sqr(x3, 3, x6); Mul(x3, x6, x6); + uint[] x9 = Create(); Sqr(x6, 3, x9); Mul(x3, x9, x9); + uint[] x18 = Create(); Sqr(x9, 9, x18); Mul(x9, x18, x18); + uint[] x19 = Create(); Sqr(x18, x19); Mul(x, x19, x19); + uint[] x37 = Create(); Sqr(x19, 18, x37); Mul(x18, x37, x37); + uint[] x74 = Create(); Sqr(x37, 37, x74); Mul(x37, x74, x74); + uint[] x111 = Create(); Sqr(x74, 37, x111); Mul(x37, x111, x111); + uint[] x222 = Create(); Sqr(x111, 111, x222); Mul(x111, x222, x222); + uint[] x223 = Create(); Sqr(x222, x223); Mul(x, x223, x223); + + uint[] t = Create(); + Sqr(x223, 223, t); + Mul(t, x222, z); + } + private static void Reduce(uint[] z, int c) { uint z15 = z[15]; @@ -836,6 +893,38 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 } } + public static bool SqrtRatioVar(uint[] u, uint[] v, uint[] z) + { + uint[] u3v = Create(); + uint[] u5v3 = Create(); + + Sqr(u, u3v); + Mul(u3v, v, u3v); + Sqr(u3v, u5v3); + Mul(u3v, u, u3v); + Mul(u5v3, u, u5v3); + Mul(u5v3, v, u5v3); + + uint[] x = Create(); + PowPm3d4(u5v3, x); + Mul(x, u3v, x); + + uint[] t = Create(); + Sqr(x, t); + Mul(t, v, t); + + Sub(u, t, t); + Normalize(t); + + if (IsZeroVar(t)) + { + Copy(x, 0, z, 0); + return true; + } + + return false; + } + public static void Sub(uint[] x, uint[] y, uint[] z) { uint x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7]; @@ -900,5 +989,13 @@ namespace Org.BouncyCastle.Math.EC.Rfc7748 z[14] = z14; z[15] = z15; } + + public static void Zero(uint[] z) + { + for (int i = 0; i < Size; ++i) + { + z[i] = 0; + } + } } } diff --git a/crypto/src/math/ec/rfc8032/Ed25519.cs b/crypto/src/math/ec/rfc8032/Ed25519.cs new file mode 100644 index 000000000..ff4587cb2 --- /dev/null +++ b/crypto/src/math/ec/rfc8032/Ed25519.cs @@ -0,0 +1,937 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Math.EC.Rfc7748; +using Org.BouncyCastle.Math.Raw; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Math.EC.Rfc8032 +{ + public abstract class Ed25519 + { + private const long M28L = 0x0FFFFFFFL; + private const long M32L = 0xFFFFFFFFL; + + private const int PointBytes = 32; + private const int ScalarUints = 8; + private const int ScalarBytes = ScalarUints * 4; + + public static readonly int PublicKeySize = PointBytes; + public static readonly int SecretKeySize = 32; + public static readonly int SignatureSize = PointBytes + ScalarBytes; + + //private static readonly byte[] Dom2Prefix = Strings.ToByteArray("SigEd25519 no Ed25519 collisions"); + + private static readonly uint[] P = { 0xFFFFFFEDU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0x7FFFFFFFU }; + private static readonly uint[] L = { 0x5CF5D3EDU, 0x5812631AU, 0xA2F79CD6U, 0x14DEF9DEU, 0x00000000U, 0x00000000U, 0x00000000U, 0x10000000U }; + + private const int L0 = unchecked((int)0xFCF5D3ED); // L0:26/-- + private const int L1 = 0x012631A6; // L1:24/22 + private const int L2 = 0x079CD658; // L2:27/-- + private const int L3 = unchecked((int)0xFF9DEA2F); // L3:23/-- + private const int L4 = 0x000014DF; // L4:12/11 + + private static readonly int[] B_x = { 0x0325D51A, 0x018B5823, 0x007B2C95, 0x0304A92D, 0x00D2598E, 0x01D6DC5C, + 0x01388C7F, 0x013FEC0A, 0x029E6B72, 0x0042D26D }; + private static readonly int[] B_y = { 0x02666658, 0x01999999, 0x00666666, 0x03333333, 0x00CCCCCC, 0x02666666, + 0x01999999, 0x00666666, 0x03333333, 0x00CCCCCC, }; + private static readonly int[] C_d = { 0x035978A3, 0x02D37284, 0x018AB75E, 0x026A0A0E, 0x0000E014, 0x0379E898, + 0x01D01E5D, 0x01E738CC, 0x03715B7F, 0x00A406D9 }; + private static readonly int[] C_d2 = { 0x02B2F159, 0x01A6E509, 0x01156EBD, 0x00D4141D, 0x0001C029, 0x02F3D130, + 0x03A03CBB, 0x01CE7198, 0x02E2B6FF, 0x00480DB3 }; + private static readonly int[] C_d4 = { 0x0165E2B2, 0x034DCA13, 0x002ADD7A, 0x01A8283B, 0x00038052, 0x01E7A260, + 0x03407977, 0x019CE331, 0x01C56DFF, 0x00901B67 }; + + private const int WnafWidthBase = 7; + + private const int PrecompBlocks = 8; + private const int PrecompTeeth = 4; + private const int PrecompSpacing = 8; + private const int PrecompPoints = 1 << (PrecompTeeth - 1); + private const int PrecompMask = PrecompPoints - 1; + + // TODO[ed25519] Convert to PointPrecomp + private static PointExt[] precompBaseTable = null; + private static int[] precompBase = null; + + private class PointAccum + { + internal int[] x = X25519Field.Create(); + internal int[] y = X25519Field.Create(); + internal int[] z = X25519Field.Create(); + internal int[] u = X25519Field.Create(); + internal int[] v = X25519Field.Create(); + } + + private class PointExt + { + internal int[] x = X25519Field.Create(); + internal int[] y = X25519Field.Create(); + internal int[] z = X25519Field.Create(); + internal int[] t = X25519Field.Create(); + } + + private class PointPrecomp + { + internal int[] ypx_h = X25519Field.Create(); + internal int[] ymx_h = X25519Field.Create(); + internal int[] xyd = X25519Field.Create(); + } + + private static byte[] CalculateS(byte[] r, byte[] k, byte[] s) + { + uint[] t = new uint[ScalarUints * 2]; DecodeScalar(r, 0, t); + uint[] u = new uint[ScalarUints]; DecodeScalar(k, 0, u); + uint[] v = new uint[ScalarUints]; DecodeScalar(s, 0, v); + + Nat256.MulAddTo(u, v, t); + + byte[] result = new byte[ScalarBytes * 2]; + for (int i = 0; i < t.Length; ++i) + { + Encode32(t[i], result, i * 4); + } + return ReduceScalar(result); + } + + private static bool CheckPointVar(byte[] p) + { + uint[] t = new uint[8]; + Decode32(p, 0, t, 0, 8); + t[7] &= 0x7FFFFFFFU; + return !Nat256.Gte(t, P); + } + + private static bool CheckScalarVar(byte[] s) + { + uint[] n = new uint[ScalarUints]; + DecodeScalar(s, 0, n); + return !Nat256.Gte(n, L); + } + + private static uint Decode24(byte[] bs, int off) + { + uint n = bs[off]; + n |= (uint)bs[++off] << 8; + n |= (uint)bs[++off] << 16; + return n; + } + + private static uint Decode32(byte[] bs, int off) + { + uint n = bs[off]; + n |= (uint)bs[++off] << 8; + n |= (uint)bs[++off] << 16; + n |= (uint)bs[++off] << 24; + return n; + } + + private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) + { + for (int i = 0; i < nLen; ++i) + { + n[nOff + i] = Decode32(bs, bsOff + i * 4); + } + } + + private static bool DecodePointVar(byte[] p, int pOff, bool negate, PointExt r) + { + byte[] py = Arrays.CopyOfRange(p, pOff, pOff + PointBytes); + if (!CheckPointVar(py)) + { + return false; + } + + int x_0 = (py[PointBytes - 1] & 0x80) >> 7; + py[PointBytes - 1] &= 0x7F; + + X25519Field.Decode(py, 0, r.y); + + int[] u = X25519Field.Create(); + int[] v = X25519Field.Create(); + + X25519Field.Sqr(r.y, u); + X25519Field.Mul(C_d, u, v); + X25519Field.SubOne(u); + X25519Field.AddOne(v); + + if (!X25519Field.SqrtRatioVar(u, v, r.x)) + { + return false; + } + + X25519Field.Normalize(r.x); + if (x_0 == 1 && X25519Field.IsZeroVar(r.x)) + { + return false; + } + + if (negate ^ (x_0 != (r.x[0] & 1))) + { + X25519Field.Negate(r.x, r.x); + } + + PointExtendXY(r); + return true; + } + + private static void DecodeScalar(byte[] k, int kOff, uint[] n) + { + Decode32(k, kOff, n, 0, ScalarUints); + } + + private static void Encode24(uint n, byte[] bs, int off) + { + bs[off] = (byte)(n); + bs[++off] = (byte)(n >> 8); + bs[++off] = (byte)(n >> 16); + } + + private static void Encode32(uint n, byte[] bs, int off) + { + bs[off] = (byte)(n); + bs[++off] = (byte)(n >> 8); + bs[++off] = (byte)(n >> 16); + bs[++off] = (byte)(n >> 24); + } + + private static void Encode56(ulong n, byte[] bs, int off) + { + Encode32((uint)n, bs, off); + Encode24((uint)(n >> 32), bs, off + 4); + } + + private static void EncodePoint(PointAccum p, byte[] r, int rOff) + { + int[] x = X25519Field.Create(); + int[] y = X25519Field.Create(); + + X25519Field.Inv(p.z, y); + X25519Field.Mul(p.x, y, x); + X25519Field.Mul(p.y, y, y); + X25519Field.Normalize(x); + X25519Field.Normalize(y); + + X25519Field.Encode(y, r, rOff); + r[rOff + PointBytes - 1] |= (byte)((x[0] & 1) << 7); + } + + public static void GeneratePublicKey(byte[] sk, int skOff, byte[] pk, int pkOff) + { + Sha512Digest d = new Sha512Digest(); + byte[] h = new byte[d.GetDigestSize()]; + + d.BlockUpdate(sk, skOff, SecretKeySize); + d.DoFinal(h, 0); + + byte[] s = new byte[ScalarBytes]; + PruneScalar(h, 0, s); + + ScalarMultBaseEncoded(s, pk, pkOff); + } + + private static sbyte[] GetWnaf(uint[] n, int width) + { + Debug.Assert(n[ScalarUints - 1] >> 31 == 0); + + uint[] t = new uint[ScalarUints * 2]; + { + uint c = 0; + int tPos = t.Length, i = ScalarUints; + while (--i >= 0) + { + uint next = n[i]; + t[--tPos] = (next >> 16) | (c << 16); + t[--tPos] = c = next; + } + } + + sbyte[] ws = new sbyte[256]; + + uint pow2 = 1U << width; + uint mask = pow2 - 1U; + uint sign = pow2 >> 1; + + uint carry = 0U; + int j = 0; + for (int i = 0; i < t.Length; ++i, j -= 16) + { + uint word = t[i]; + while (j < 16) + { + uint word16 = word >> j; + uint bit = word16 & 1U; + + if (bit == carry) + { + ++j; + continue; + } + + uint digit = (word16 & mask) + carry; + carry = digit & sign; + digit -= (carry << 1); + carry >>= (width - 1); + + ws[(i << 4) + j] = (sbyte)digit; + + j += width; + } + } + + Debug.Assert(carry == 0); + + return ws; + } + + private static void ImplSign(Sha512Digest d, byte[] h, byte[] s, byte[] pk, int pkOff, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) + { + d.BlockUpdate(h, ScalarBytes, ScalarBytes); + d.BlockUpdate(m, mOff, mLen); + d.DoFinal(h, 0); + + byte[] r = ReduceScalar(h); + byte[] R = new byte[PointBytes]; + ScalarMultBaseEncoded(r, R, 0); + + d.BlockUpdate(R, 0, PointBytes); + d.BlockUpdate(pk, 0, PointBytes); + d.BlockUpdate(m, mOff, mLen); + d.DoFinal(h, 0); + + byte[] k = ReduceScalar(h); + byte[] S = CalculateS(r, k, s); + + Array.Copy(R, 0, sig, sigOff, PointBytes); + Array.Copy(S, 0, sig, sigOff + PointBytes, ScalarBytes); + } + + private static void PointAddVar(bool negate, PointExt p, PointAccum r) + { + int[] A = X25519Field.Create(); + int[] B = X25519Field.Create(); + int[] C = X25519Field.Create(); + int[] D = X25519Field.Create(); + int[] E = r.u; + int[] F = X25519Field.Create(); + int[] G = X25519Field.Create(); + int[] H = r.v; + + int[] c, d, f, g; + if (negate) + { + c = D; d = C; f = G; g = F; + } + else + { + c = C; d = D; f = F; g = G; + } + + X25519Field.Apm(r.y, r.x, B, A); + X25519Field.Apm(p.y, p.x, d, c); + X25519Field.Mul(A, C, A); + X25519Field.Mul(B, D, B); + X25519Field.Mul(r.u, r.v, C); + X25519Field.Mul(C, p.t, C); + X25519Field.Mul(C, C_d2, C); + X25519Field.Mul(r.z, p.z, D); + X25519Field.Add(D, D, D); + X25519Field.Apm(B, A, H, E); + X25519Field.Apm(D, C, g, f); + X25519Field.Carry(g); + X25519Field.Mul(E, F, r.x); + X25519Field.Mul(G, H, r.y); + X25519Field.Mul(F, G, r.z); + } + + private static void PointAddVar(bool negate, PointExt p, PointExt q, PointExt r) + { + int[] A = X25519Field.Create(); + int[] B = X25519Field.Create(); + int[] C = X25519Field.Create(); + int[] D = X25519Field.Create(); + int[] E = X25519Field.Create(); + int[] F = X25519Field.Create(); + int[] G = X25519Field.Create(); + int[] H = X25519Field.Create(); + + int[] c, d, f, g; + if (negate) + { + c = D; d = C; f = G; g = F; + } + else + { + c = C; d = D; f = F; g = G; + } + + X25519Field.Apm(p.y, p.x, B, A); + X25519Field.Apm(q.y, q.x, d, c); + X25519Field.Mul(A, C, A); + X25519Field.Mul(B, D, B); + X25519Field.Mul(p.t, q.t, C); + X25519Field.Mul(C, C_d2, C); + X25519Field.Mul(p.z, q.z, D); + X25519Field.Add(D, D, D); + X25519Field.Apm(B, A, H, E); + X25519Field.Apm(D, C, g, f); + X25519Field.Carry(g); + X25519Field.Mul(E, F, r.x); + X25519Field.Mul(G, H, r.y); + X25519Field.Mul(F, G, r.z); + X25519Field.Mul(E, H, r.t); + } + + private static void PointAddPrecomp(PointPrecomp p, PointAccum r) + { + int[] A = X25519Field.Create(); + int[] B = X25519Field.Create(); + int[] C = X25519Field.Create(); + int[] E = r.u; + int[] F = X25519Field.Create(); + int[] G = X25519Field.Create(); + int[] H = r.v; + + X25519Field.Apm(r.y, r.x, B, A); + X25519Field.Mul(A, p.ymx_h, A); + X25519Field.Mul(B, p.ypx_h, B); + X25519Field.Mul(r.u, r.v, C); + X25519Field.Mul(C, p.xyd, C); + X25519Field.Apm(B, A, H, E); + X25519Field.Apm(r.z, C, G, F); + X25519Field.Carry(G); + X25519Field.Mul(E, F, r.x); + X25519Field.Mul(G, H, r.y); + X25519Field.Mul(F, G, r.z); + } + + private static PointExt PointCopy(PointAccum p) + { + PointExt r = new PointExt(); + X25519Field.Copy(p.x, 0, r.x, 0); + X25519Field.Copy(p.y, 0, r.y, 0); + X25519Field.Copy(p.z, 0, r.z, 0); + X25519Field.Mul(p.u, p.v, r.t); + return r; + } + + private static PointExt PointCopy(PointExt p) + { + PointExt r = new PointExt(); + X25519Field.Copy(p.x, 0, r.x, 0); + X25519Field.Copy(p.y, 0, r.y, 0); + X25519Field.Copy(p.z, 0, r.z, 0); + X25519Field.Copy(p.t, 0, r.t, 0); + return r; + } + + private static void PointDouble(PointAccum r) + { + int[] A = X25519Field.Create(); + int[] B = X25519Field.Create(); + int[] C = X25519Field.Create(); + int[] E = r.u; + int[] F = X25519Field.Create(); + int[] G = X25519Field.Create(); + int[] H = r.v; + + X25519Field.Sqr(r.x, A); + X25519Field.Sqr(r.y, B); + X25519Field.Sqr(r.z, C); + X25519Field.Add(C, C, C); + X25519Field.Apm(A, B, H, G); + X25519Field.Add(r.x, r.y, E); + X25519Field.Sqr(E, E); + X25519Field.Sub(H, E, E); + X25519Field.Add(C, G, F); + X25519Field.Carry(F); + X25519Field.Mul(E, F, r.x); + X25519Field.Mul(G, H, r.y); + X25519Field.Mul(F, G, r.z); + } + + private static void PointExtendXY(PointAccum p) + { + X25519Field.One(p.z); + X25519Field.Copy(p.x, 0, p.u, 0); + X25519Field.Copy(p.y, 0, p.v, 0); + } + + private static void PointExtendXY(PointExt p) + { + X25519Field.One(p.z); + X25519Field.Mul(p.x, p.y, p.t); + } + + private static void PointLookup(int block, int index, PointPrecomp p) + { + Debug.Assert(0 <= block && block < PrecompBlocks); + Debug.Assert(0 <= index && index < PrecompPoints); + + int off = block * PrecompPoints * 3 * X25519Field.Size; + + for (int i = 0; i < PrecompPoints; ++i) + { + int mask = ((i ^ index) - 1) >> 31; + Nat.CMov(X25519Field.Size, mask, precompBase, off, p.ypx_h, 0); off += X25519Field.Size; + Nat.CMov(X25519Field.Size, mask, precompBase, off, p.ymx_h, 0); off += X25519Field.Size; + Nat.CMov(X25519Field.Size, mask, precompBase, off, p.xyd, 0); off += X25519Field.Size; + } + } + + private static PointExt[] PointPrecompVar(PointExt p, int count) + { + Debug.Assert(count > 0); + + PointExt d = new PointExt(); + PointAddVar(false, p, p, d); + + PointExt[] table = new PointExt[count]; + table[0] = PointCopy(p); + for (int i = 1; i < count; ++i) + { + PointAddVar(false, table[i - 1], d, table[i] = new PointExt()); + } + return table; + } + + private static void PointSetNeutral(PointAccum p) + { + X25519Field.Zero(p.x); + X25519Field.One(p.y); + X25519Field.One(p.z); + X25519Field.Zero(p.u); + X25519Field.One(p.v); + } + + private static void PointSetNeutral(PointExt p) + { + X25519Field.Zero(p.x); + X25519Field.One(p.y); + X25519Field.One(p.z); + X25519Field.Zero(p.t); + } + + [MethodImpl(MethodImplOptions.Synchronized)] + public static void Precompute() + { + if (precompBase != null) + { + return; + } + + // Precomputed table for the base point in verification ladder + { + PointExt b = new PointExt(); + X25519Field.Copy(B_x, 0, b.x, 0); + X25519Field.Copy(B_y, 0, b.y, 0); + PointExtendXY(b); + + precompBaseTable = PointPrecompVar(b, 1 << (WnafWidthBase - 2)); + } + + PointAccum p = new PointAccum(); + X25519Field.Copy(B_x, 0, p.x, 0); + X25519Field.Copy(B_y, 0, p.y, 0); + PointExtendXY(p); + + precompBase = new int[PrecompBlocks * PrecompPoints * 3 * X25519Field.Size]; + + int off = 0; + for (int b = 0; b < PrecompBlocks; ++b) + { + PointExt[] ds = new PointExt[PrecompTeeth]; + + PointExt sum = new PointExt(); + PointSetNeutral(sum); + + for (int t = 0; t < PrecompTeeth; ++t) + { + PointExt q = PointCopy(p); + PointAddVar(true, sum, q, sum); + PointDouble(p); + + ds[t] = PointCopy(p); + + for (int s = 1; s < PrecompSpacing; ++s) + { + PointDouble(p); + } + } + + PointExt[] points = new PointExt[PrecompPoints]; + int k = 0; + points[k++] = sum; + + for (int t = 0; t < (PrecompTeeth - 1); ++t) + { + int size = 1 << t; + for (int j = 0; j < size; ++j, ++k) + { + PointAddVar(false, points[k - size], ds[t], points[k] = new PointExt()); + } + } + + Debug.Assert(k == PrecompPoints); + + for (int i = 0; i < PrecompPoints; ++i) + { + PointExt q = points[i]; + + int[] x = X25519Field.Create(); + int[] y = X25519Field.Create(); + + X25519Field.Add(q.z, q.z, x); + // TODO[ed25519] Batch inversion + X25519Field.Inv(x, y); + X25519Field.Mul(q.x, y, x); + X25519Field.Mul(q.y, y, y); + + PointPrecomp r = new PointPrecomp(); + X25519Field.Apm(y, x, r.ypx_h, r.ymx_h); + X25519Field.Mul(x, y, r.xyd); + X25519Field.Mul(r.xyd, C_d4, r.xyd); + + X25519Field.Normalize(r.ypx_h); + X25519Field.Normalize(r.ymx_h); + //X25519Field.Normalize(r.xyd); + + X25519Field.Copy(r.ypx_h, 0, precompBase, off); off += X25519Field.Size; + X25519Field.Copy(r.ymx_h, 0, precompBase, off); off += X25519Field.Size; + X25519Field.Copy(r.xyd, 0, precompBase, off); off += X25519Field.Size; + } + } + + Debug.Assert(off == precompBase.Length); + } + + private static void PruneScalar(byte[] n, int nOff, byte[] r) + { + Array.Copy(n, nOff, r, 0, ScalarBytes); + + r[0] &= 0xF8; + r[ScalarBytes - 1] &= 0x7F; + r[ScalarBytes - 1] |= 0x40; + } + + private static byte[] ReduceScalar(byte[] n) + { + long x00 = Decode32(n, 0) & M32L; // x00:32/-- + long x01 = (Decode24(n, 4) << 4) & M32L; // x01:28/-- + long x02 = Decode32(n, 7) & M32L; // x02:32/-- + long x03 = (Decode24(n, 11) << 4) & M32L; // x03:28/-- + long x04 = Decode32(n, 14) & M32L; // x04:32/-- + long x05 = (Decode24(n, 18) << 4) & M32L; // x05:28/-- + long x06 = Decode32(n, 21) & M32L; // x06:32/-- + long x07 = (Decode24(n, 25) << 4) & M32L; // x07:28/-- + long x08 = Decode32(n, 28) & M32L; // x08:32/-- + long x09 = (Decode24(n, 32) << 4) & M32L; // x09:28/-- + long x10 = Decode32(n, 35) & M32L; // x10:32/-- + long x11 = (Decode24(n, 39) << 4) & M32L; // x11:28/-- + long x12 = Decode32(n, 42) & M32L; // x12:32/-- + long x13 = (Decode24(n, 46) << 4) & M32L; // x13:28/-- + long x14 = Decode32(n, 49) & M32L; // x14:32/-- + long x15 = (Decode24(n, 53) << 4) & M32L; // x15:28/-- + long x16 = Decode32(n, 56) & M32L; // x16:32/-- + long x17 = (Decode24(n, 60) << 4) & M32L; // x17:28/-- + long x18 = n[63] & 0xFFL; // x18:08/-- + long t; + + //x18 += (x17 >> 28); x17 &= M28L; + x09 -= x18 * L0; // x09:34/28 + x10 -= x18 * L1; // x10:33/30 + x11 -= x18 * L2; // x11:35/28 + x12 -= x18 * L3; // x12:32/31 + x13 -= x18 * L4; // x13:28/21 + + x17 += (x16 >> 28); x16 &= M28L; // x17:28/--, x16:28/-- + x08 -= x17 * L0; // x08:54/32 + x09 -= x17 * L1; // x09:52/51 + x10 -= x17 * L2; // x10:55/34 + x11 -= x17 * L3; // x11:51/36 + x12 -= x17 * L4; // x12:41/-- + + //x16 += (x15 >> 28); x15 &= M28L; + x07 -= x16 * L0; // x07:54/28 + x08 -= x16 * L1; // x08:54/53 + x09 -= x16 * L2; // x09:55/53 + x10 -= x16 * L3; // x10:55/52 + x11 -= x16 * L4; // x11:51/41 + + x15 += (x14 >> 28); x14 &= M28L; // x15:28/--, x14:28/-- + x06 -= x15 * L0; // x06:54/32 + x07 -= x15 * L1; // x07:54/53 + x08 -= x15 * L2; // x08:56/-- + x09 -= x15 * L3; // x09:55/54 + x10 -= x15 * L4; // x10:55/53 + + //x14 += (x13 >> 28); x13 &= M28L; + x05 -= x14 * L0; // x05:54/28 + x06 -= x14 * L1; // x06:54/53 + x07 -= x14 * L2; // x07:56/-- + x08 -= x14 * L3; // x08:56/51 + x09 -= x14 * L4; // x09:56/-- + + x13 += (x12 >> 28); x12 &= M28L; // x13:28/22, x12:28/-- + x04 -= x13 * L0; // x04:54/49 + x05 -= x13 * L1; // x05:54/53 + x06 -= x13 * L2; // x06:56/-- + x07 -= x13 * L3; // x07:56/52 + x08 -= x13 * L4; // x08:56/52 + + x12 += (x11 >> 28); x11 &= M28L; // x12:28/24, x11:28/-- + x03 -= x12 * L0; // x03:54/49 + x04 -= x12 * L1; // x04:54/51 + x05 -= x12 * L2; // x05:56/-- + x06 -= x12 * L3; // x06:56/52 + x07 -= x12 * L4; // x07:56/53 + + x11 += (x10 >> 28); x10 &= M28L; // x11:29/--, x10:28/-- + x02 -= x11 * L0; // x02:55/32 + x03 -= x11 * L1; // x03:55/-- + x04 -= x11 * L2; // x04:56/55 + x05 -= x11 * L3; // x05:56/52 + x06 -= x11 * L4; // x06:56/53 + + x10 += (x09 >> 28); x09 &= M28L; // x10:29/--, x09:28/-- + x01 -= x10 * L0; // x01:55/28 + x02 -= x10 * L1; // x02:55/54 + x03 -= x10 * L2; // x03:56/55 + x04 -= x10 * L3; // x04:57/-- + x05 -= x10 * L4; // x05:56/53 + + x08 += (x07 >> 28); x07 &= M28L; // x08:56/53, x07:28/-- + x09 += (x08 >> 28); x08 &= M28L; // x09:29/25, x08:28/-- + + t = (x08 >> 27) & 1L; + x09 += t; // x09:29/26 + + x00 -= x09 * L0; // x00:55/53 + x01 -= x09 * L1; // x01:55/54 + x02 -= x09 * L2; // x02:57/-- + x03 -= x09 * L3; // x03:57/-- + x04 -= x09 * L4; // x04:57/42 + + x01 += (x00 >> 28); x00 &= M28L; + x02 += (x01 >> 28); x01 &= M28L; + x03 += (x02 >> 28); x02 &= M28L; + x04 += (x03 >> 28); x03 &= M28L; + x05 += (x04 >> 28); x04 &= M28L; + x06 += (x05 >> 28); x05 &= M28L; + x07 += (x06 >> 28); x06 &= M28L; + x08 += (x07 >> 28); x07 &= M28L; + x09 = (x08 >> 28); x08 &= M28L; + + x09 -= t; + + Debug.Assert(x09 == 0L || x09 == -1L); + + x00 += x09 & L0; + x01 += x09 & L1; + x02 += x09 & L2; + x03 += x09 & L3; + x04 += x09 & L4; + + x01 += (x00 >> 28); x00 &= M28L; + x02 += (x01 >> 28); x01 &= M28L; + x03 += (x02 >> 28); x02 &= M28L; + x04 += (x03 >> 28); x03 &= M28L; + x05 += (x04 >> 28); x04 &= M28L; + x06 += (x05 >> 28); x05 &= M28L; + x07 += (x06 >> 28); x06 &= M28L; + x08 += (x07 >> 28); x07 &= M28L; + + byte[] r = new byte[ScalarBytes]; + Encode56((ulong)(x00 | (x01 << 28)), r, 0); + Encode56((ulong)(x02 | (x03 << 28)), r, 7); + Encode56((ulong)(x04 | (x05 << 28)), r, 14); + Encode56((ulong)(x06 | (x07 << 28)), r, 21); + Encode32((uint)x08, r, 28); + return r; + } + + private static void ScalarMultBase(byte[] k, PointAccum r) + { + Precompute(); + + PointSetNeutral(r); + + uint[] n = new uint[ScalarUints]; + DecodeScalar(k, 0, n); + + // Recode the scalar into signed-digit form, then group comb bits in each block + { + uint c1 = Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); Debug.Assert(c1 == 0); + uint c2 = Nat.ShiftDownBit(ScalarUints, n, 1U); Debug.Assert(c2 == (1U << 31)); + + for (int i = 0; i < ScalarUints; ++i) + { + n[i] = Interleave.Shuffle2(n[i]); + } + } + + PointPrecomp p = new PointPrecomp(); + + int cOff = (PrecompSpacing - 1) * PrecompTeeth; + for (; ; ) + { + for (int b = 0; b < PrecompBlocks; ++b) + { + uint w = n[b] >> cOff; + int sign = (int)(w >> (PrecompTeeth - 1)) & 1; + int abs = ((int)w ^ -sign) & PrecompMask; + + Debug.Assert(sign == 0 || sign == 1); + Debug.Assert(0 <= abs && abs < PrecompPoints); + + PointLookup(b, abs, p); + + X25519Field.CSwap(sign, p.ypx_h, p.ymx_h); + X25519Field.CNegate(sign, p.xyd); + + PointAddPrecomp(p, r); + } + + if ((cOff -= PrecompTeeth) < 0) + { + break; + } + + PointDouble(r); + } + } + + private static void ScalarMultBaseEncoded(byte[] k, byte[] r, int rOff) + { + PointAccum p = new PointAccum(); + ScalarMultBase(k, p); + EncodePoint(p, r, rOff); + } + + private static void ScalarMultStraussVar(uint[] nb, uint[] np, PointExt p, PointAccum r) + { + Precompute(); + + int width = 5; + + sbyte[] ws_b = GetWnaf(nb, WnafWidthBase); + sbyte[] ws_p = GetWnaf(np, width); + + PointExt[] tp = PointPrecompVar(p, 1 << (width - 2)); + + PointSetNeutral(r); + + int bit = 255; + while (bit > 0 && (ws_b[bit] | ws_p[bit]) == 0) + { + --bit; + } + + for (; ; ) + { + int wb = ws_b[bit]; + if (wb != 0) + { + int sign = wb >> 31; + int index = (wb ^ sign) >> 1; + + PointAddVar((sign != 0), precompBaseTable[index], r); + } + + int wp = ws_p[bit]; + if (wp != 0) + { + int sign = wp >> 31; + int index = (wp ^ sign) >> 1; + + PointAddVar((sign != 0), tp[index], r); + } + + if (--bit < 0) + { + break; + } + + PointDouble(r); + } + } + + public static void Sign(byte[] sk, int skOff, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) + { + Sha512Digest d = new Sha512Digest(); + byte[] h = new byte[d.GetDigestSize()]; + + d.BlockUpdate(sk, skOff, SecretKeySize); + d.DoFinal(h, 0); + + byte[] s = new byte[ScalarBytes]; + PruneScalar(h, 0, s); + + byte[] pk = new byte[PointBytes]; + ScalarMultBaseEncoded(s, pk, 0); + + ImplSign(d, h, s, pk, 0, m, mOff, mLen, sig, sigOff); + } + + public static void Sign(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) + { + Sha512Digest d = new Sha512Digest(); + byte[] h = new byte[d.GetDigestSize()]; + + d.BlockUpdate(sk, skOff, SecretKeySize); + d.DoFinal(h, 0); + + byte[] s = new byte[ScalarBytes]; + PruneScalar(h, 0, s); + + ImplSign(d, h, s, pk, pkOff, m, mOff, mLen, sig, sigOff); + } + + public static bool Verify(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] m, int mOff, int mLen) + { + byte[] R = Arrays.CopyOfRange(sig, sigOff, sigOff + PointBytes); + byte[] S = Arrays.CopyOfRange(sig, sigOff + PointBytes, sigOff + SignatureSize); + + if (!CheckPointVar(R)) + { + return false; + } + if (!CheckScalarVar(S)) + { + return false; + } + + PointExt pA = new PointExt(); + if (!DecodePointVar(pk, pkOff, true, pA)) + { + return false; + } + + Sha512Digest d = new Sha512Digest(); + byte[] h = new byte[d.GetDigestSize()]; + + d.BlockUpdate(R, 0, PointBytes); + d.BlockUpdate(pk, pkOff, PointBytes); + d.BlockUpdate(m, mOff, mLen); + d.DoFinal(h, 0); + + byte[] k = ReduceScalar(h); + + uint[] nS = new uint[ScalarUints]; + DecodeScalar(S, 0, nS); + + uint[] nA = new uint[ScalarUints]; + DecodeScalar(k, 0, nA); + + PointAccum pR = new PointAccum(); + ScalarMultStraussVar(nS, nA, pA, pR); + + byte[] check = new byte[PointBytes]; + EncodePoint(pR, check, 0); + + return Arrays.AreEqual(check, R); + } + } +} diff --git a/crypto/src/math/ec/rfc8032/Ed448.cs b/crypto/src/math/ec/rfc8032/Ed448.cs new file mode 100644 index 000000000..52c215160 --- /dev/null +++ b/crypto/src/math/ec/rfc8032/Ed448.cs @@ -0,0 +1,1067 @@ +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; + +using Org.BouncyCastle.Crypto.Digests; +using Org.BouncyCastle.Math.EC.Rfc7748; +using Org.BouncyCastle.Math.Raw; +using Org.BouncyCastle.Utilities; + +namespace Org.BouncyCastle.Math.EC.Rfc8032 +{ + public abstract class Ed448 + { + private const ulong M26UL = 0x03FFFFFFUL; + private const ulong M28UL = 0x0FFFFFFFUL; + + private const int PointBytes = 57; + private const int ScalarUints = 14; + private const int ScalarBytes = ScalarUints * 4 + 1; + + public static readonly int PublicKeySize = PointBytes; + public static readonly int SecretKeySize = 57; + public static readonly int SignatureSize = PointBytes + ScalarBytes; + + private static readonly byte[] Dom4Prefix = Strings.ToByteArray("SigEd448"); + + private static readonly uint[] P = { 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, + 0xFFFFFFFEU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU }; + private static readonly uint[] L = { 0xAB5844F3U, 0x2378C292U, 0x8DC58F55U, 0x216CC272U, 0xAED63690U, 0xC44EDB49U, 0x7CCA23E9U, + 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0xFFFFFFFFU, 0x3FFFFFFFU }; + private static readonly BigInteger N = Nat.ToBigInteger(L.Length, L); + + private const int L_0 = 0x04A7BB0D; // L_0:26/24 + private const int L_1 = 0x0873D6D5; // L_1:27/23 + private const int L_2 = 0x0A70AADC; // L_2:27/26 + private const int L_3 = 0x03D8D723; // L_3:26/-- + private const int L_4 = 0x096FDE93; // L_4:27/25 + private const int L_5 = 0x0B65129C; // L_5:27/26 + private const int L_6 = 0x063BB124; // L_6:27/-- + private const int L_7 = 0x08335DC1; // L_7:27/22 + + private const int L4_0 = 0x029EEC34; // L4_0:25/24 + private const int L4_1 = 0x01CF5B55; // L4_1:25/-- + private const int L4_2 = 0x09C2AB72; // L4_2:27/25 + private const int L4_3 = 0x0F635C8E; // L4_3:28/-- + private const int L4_4 = 0x05BF7A4C; // L4_4:26/25 + private const int L4_5 = 0x0D944A72; // L4_5:28/-- + private const int L4_6 = 0x08EEC492; // L4_6:27/24 + private const int L4_7 = 0x20CD7705; // L4_7:29/24 + + private static readonly uint[] B_x = { 0x070CC05EU, 0x026A82BCU, 0x00938E26U, 0x080E18B0U, 0x0511433BU, 0x0F72AB66U, 0x0412AE1AU, + 0x0A3D3A46U, 0x0A6DE324U, 0x00F1767EU, 0x04657047U, 0x036DA9E1U, 0x05A622BFU, 0x0ED221D1U, 0x066BED0DU, 0x04F1970CU }; + private static readonly uint[] B_y = { 0x0230FA14U, 0x008795BFU, 0x07C8AD98U, 0x0132C4EDU, 0x09C4FDBDU, 0x01CE67C3U, 0x073AD3FFU, + 0x005A0C2DU, 0x07789C1EU, 0x0A398408U, 0x0A73736CU, 0x0C7624BEU, 0x003756C9U, 0x02488762U, 0x016EB6BCU, 0x0693F467U }; + private const int C_d = -39081; + + private const int WnafWidthBase = 7; + + private const int PrecompBlocks = 5; + private const int PrecompTeeth = 5; + private const int PrecompSpacing = 18; + private const int PrecompPoints = 1 << (PrecompTeeth - 1); + private const int PrecompMask = PrecompPoints - 1; + + // TODO[ed448] Convert to PointPrecomp + private static PointExt[] precompBaseTable = null; + private static uint[] precompBase = null; + + private class PointExt + { + internal uint[] x = X448Field.Create(); + internal uint[] y = X448Field.Create(); + internal uint[] z = X448Field.Create(); + } + + private class PointPrecomp + { + internal uint[] x = X448Field.Create(); + internal uint[] y = X448Field.Create(); + } + + private static byte[] CalculateS(byte[] r, byte[] k, byte[] s) + { + uint[] t = new uint[ScalarUints * 2]; DecodeScalar(r, 0, t); + uint[] u = new uint[ScalarUints]; DecodeScalar(k, 0, u); + uint[] v = new uint[ScalarUints]; DecodeScalar(s, 0, v); + + Nat.MulAddTo(14, u, v, t); + + byte[] result = new byte[ScalarBytes * 2]; + for (int i = 0; i < t.Length; ++i) + { + Encode32(t[i], result, i * 4); + } + return ReduceScalar(result); + } + + private static bool CheckContextVar(byte[] ctx) + { + return ctx != null && ctx.Length < 256; + } + + private static bool CheckPointVar(byte[] p) + { + if ((p[PointBytes - 1] & 0x7F) != 0x00) + { + return false; + } + + uint[] t = new uint[14]; + Decode32(p, 0, t, 0, 14); + return !Nat.Gte(14, t, P); + } + + private static bool CheckScalarVar(byte[] s) + { + if (s[ScalarBytes - 1] != 0x00) + { + return false; + } + + uint[] n = new uint[ScalarUints]; + DecodeScalar(s, 0, n); + return !Nat.Gte(ScalarUints, n, L); + } + + private static uint Decode16(byte[] bs, int off) + { + uint n = bs[off]; + n |= (uint)bs[++off] << 8; + return n; + } + + private static uint Decode24(byte[] bs, int off) + { + uint n = bs[off]; + n |= (uint)bs[++off] << 8; + n |= (uint)bs[++off] << 16; + return n; + } + + private static uint Decode32(byte[] bs, int off) + { + uint n = bs[off]; + n |= (uint)bs[++off] << 8; + n |= (uint)bs[++off] << 16; + n |= (uint)bs[++off] << 24; + return n; + } + + private static void Decode32(byte[] bs, int bsOff, uint[] n, int nOff, int nLen) + { + for (int i = 0; i < nLen; ++i) + { + n[nOff + i] = Decode32(bs, bsOff + i * 4); + } + } + + private static bool DecodePointVar(byte[] p, int pOff, bool negate, PointExt r) + { + byte[] py = Arrays.CopyOfRange(p, pOff, pOff + PointBytes); + if (!CheckPointVar(py)) + { + return false; + } + + int x_0 = (py[PointBytes - 1] & 0x80) >> 7; + py[PointBytes - 1] &= 0x7F; + + X448Field.Decode(py, 0, r.y); + + uint[] u = X448Field.Create(); + uint[] v = X448Field.Create(); + + X448Field.Sqr(r.y, u); + X448Field.Mul(u, (uint)-C_d, v); + X448Field.Negate(u, u); + X448Field.AddOne(u); + X448Field.AddOne(v); + + if (!X448Field.SqrtRatioVar(u, v, r.x)) + { + return false; + } + + X448Field.Normalize(r.x); + if (x_0 == 1 && X448Field.IsZeroVar(r.x)) + { + return false; + } + + if (negate ^ (x_0 != (r.x[0] & 1))) + { + X448Field.Negate(r.x, r.x); + } + + PointExtendXY(r); + return true; + } + + private static void DecodeScalar(byte[] k, int kOff, uint[] n) + { + Debug.Assert(k[kOff + ScalarBytes - 1] == 0x00); + + Decode32(k, kOff, n, 0, ScalarUints); + } + + private static void Dom4(ShakeDigest d, byte x, byte[] y) + { + d.BlockUpdate(Dom4Prefix, 0, Dom4Prefix.Length); + d.Update(x); + d.Update((byte)y.Length); + d.BlockUpdate(y, 0, y.Length); + } + + private static void Encode24(uint n, byte[] bs, int off) + { + bs[off] = (byte)(n); + bs[++off] = (byte)(n >> 8); + bs[++off] = (byte)(n >> 16); + } + + private static void Encode32(uint n, byte[] bs, int off) + { + bs[off] = (byte)(n); + bs[++off] = (byte)(n >> 8); + bs[++off] = (byte)(n >> 16); + bs[++off] = (byte)(n >> 24); + } + + private static void Encode56(ulong n, byte[] bs, int off) + { + Encode32((uint)n, bs, off); + Encode24((uint)(n >> 32), bs, off + 4); + } + + private static void EncodePoint(PointExt p, byte[] r, int rOff) + { + uint[] x = X448Field.Create(); + uint[] y = X448Field.Create(); + + X448Field.Inv(p.z, y); + X448Field.Mul(p.x, y, x); + X448Field.Mul(p.y, y, y); + X448Field.Normalize(x); + X448Field.Normalize(y); + + X448Field.Encode(y, r, rOff); + r[rOff + PointBytes - 1] = (byte)((x[0] & 1) << 7); + } + + public static void GeneratePublicKey(byte[] sk, int skOff, byte[] pk, int pkOff) + { + ShakeDigest d = new ShakeDigest(256); + byte[] h = new byte[ScalarBytes * 2]; + + d.BlockUpdate(sk, skOff, SecretKeySize); + d.DoFinal(h, 0, h.Length); + + byte[] s = new byte[ScalarBytes]; + PruneScalar(h, 0, s); + + ScalarMultBaseEncoded(s, pk, pkOff); + } + + private static sbyte[] GetWnaf(uint[] n, int width) + { + Debug.Assert(n[ScalarUints - 1] >> 31 == 0U); + + uint[] t = new uint[ScalarUints * 2]; + { + uint c = 0; + int tPos = t.Length, i = ScalarUints; + while (--i >= 0) + { + uint next = n[i]; + t[--tPos] = (next >> 16) | (c << 16); + t[--tPos] = c = next; + } + } + + sbyte[] ws = new sbyte[448]; + + uint pow2 = 1U << width; + uint mask = pow2 - 1U; + uint sign = pow2 >> 1; + + uint carry = 0U; + int j = 0; + for (int i = 0; i < t.Length; ++i, j -= 16) + { + uint word = t[i]; + while (j < 16) + { + uint word16 = word >> j; + uint bit = word16 & 1U; + + if (bit == carry) + { + ++j; + continue; + } + + uint digit = (word16 & mask) + carry; + carry = digit & sign; + digit -= (carry << 1); + carry >>= (width - 1); + + ws[(i << 4) + j] = (sbyte)digit; + + j += width; + } + } + + Debug.Assert(carry == 0); + + return ws; + } + + private static void ImplSign(ShakeDigest d, byte[] h, byte[] s, byte[] pk, int pkOff, byte[] ctx, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) + { + byte phflag = 0x00; + + Dom4(d, phflag, ctx); + d.BlockUpdate(h, ScalarBytes, ScalarBytes); + d.BlockUpdate(m, mOff, mLen); + d.DoFinal(h, 0, h.Length); + + byte[] r = ReduceScalar(h); + byte[] R = new byte[PointBytes]; + ScalarMultBaseEncoded(r, R, 0); + + Dom4(d, phflag, ctx); + d.BlockUpdate(R, 0, PointBytes); + d.BlockUpdate(pk, pkOff, PointBytes); + d.BlockUpdate(m, mOff, mLen); + d.DoFinal(h, 0, h.Length); + + byte[] k = ReduceScalar(h); + byte[] S = CalculateS(r, k, s); + + Array.Copy(R, 0, sig, sigOff, PointBytes); + Array.Copy(S, 0, sig, sigOff + PointBytes, ScalarBytes); + } + + private static void PointAddVar(bool negate, PointExt p, PointExt r) + { + uint[] A = X448Field.Create(); + uint[] B = X448Field.Create(); + uint[] C = X448Field.Create(); + uint[] D = X448Field.Create(); + uint[] E = X448Field.Create(); + uint[] F = X448Field.Create(); + uint[] G = X448Field.Create(); + uint[] H = X448Field.Create(); + + uint[] b, e, f, g; + if (negate) + { + b = E; e = B; f = G; g = F; + X448Field.Sub(p.y, p.x, H); + } + else + { + b = B; e = E; f = F; g = G; + X448Field.Add(p.y, p.x, H); + } + + X448Field.Mul(p.z, r.z, A); + X448Field.Sqr(A, B); + X448Field.Mul(p.x, r.x, C); + X448Field.Mul(p.y, r.y, D); + X448Field.Mul(C, D, E); + X448Field.Mul(E, -C_d, E); + // X448Field.Apm(B, E, F, G); + X448Field.Add(B, E, f); + X448Field.Sub(B, E, g); + X448Field.Add(r.x, r.y, E); + X448Field.Mul(H, E, H); + // X448Field.Apm(D, C, B, E); + X448Field.Add(D, C, b); + X448Field.Sub(D, C, e); + X448Field.Carry(b); + X448Field.Sub(H, B, H); + X448Field.Mul(H, A, H); + X448Field.Mul(E, A, E); + X448Field.Mul(F, H, r.x); + X448Field.Mul(E, G, r.y); + X448Field.Mul(F, G, r.z); + } + + private static void PointAddPrecomp(PointPrecomp p, PointExt r) + { + uint[] B = X448Field.Create(); + uint[] C = X448Field.Create(); + uint[] D = X448Field.Create(); + uint[] E = X448Field.Create(); + uint[] F = X448Field.Create(); + uint[] G = X448Field.Create(); + uint[] H = X448Field.Create(); + + X448Field.Sqr(r.z, B); + X448Field.Mul(p.x, r.x, C); + X448Field.Mul(p.y, r.y, D); + X448Field.Mul(C, D, E); + X448Field.Mul(E, -C_d, E); + // X448Field.Apm(B, E, F, G); + X448Field.Add(B, E, F); + X448Field.Sub(B, E, G); + X448Field.Add(p.x, p.y, B); + X448Field.Add(r.x, r.y, E); + X448Field.Mul(B, E, H); + // X448Field.Apm(D, C, B, E); + X448Field.Add(D, C, B); + X448Field.Sub(D, C, E); + X448Field.Carry(B); + X448Field.Sub(H, B, H); + X448Field.Mul(H, r.z, H); + X448Field.Mul(E, r.z, E); + X448Field.Mul(F, H, r.x); + X448Field.Mul(E, G, r.y); + X448Field.Mul(F, G, r.z); + } + + private static PointExt PointCopy(PointExt p) + { + PointExt r = new PointExt(); + X448Field.Copy(p.x, 0, r.x, 0); + X448Field.Copy(p.y, 0, r.y, 0); + X448Field.Copy(p.z, 0, r.z, 0); + return r; + } + + private static void PointDouble(PointExt r) + { + uint[] B = X448Field.Create(); + uint[] C = X448Field.Create(); + uint[] D = X448Field.Create(); + uint[] E = X448Field.Create(); + uint[] H = X448Field.Create(); + uint[] J = X448Field.Create(); + + X448Field.Add(r.x, r.y, B); + X448Field.Sqr(B, B); + X448Field.Sqr(r.x, C); + X448Field.Sqr(r.y, D); + X448Field.Add(C, D, E); + X448Field.Carry(E); + X448Field.Sqr(r.z, H); + X448Field.Add(H, H, H); + X448Field.Carry(H); + X448Field.Sub(E, H, J); + X448Field.Sub(B, E, B); + X448Field.Sub(C, D, C); + X448Field.Mul(B, J, r.x); + X448Field.Mul(E, C, r.y); + X448Field.Mul(E, J, r.z); + } + + private static void PointExtendXY(PointExt p) + { + X448Field.One(p.z); + } + + private static void PointLookup(int block, int index, PointPrecomp p) + { + Debug.Assert(0 <= block && block < PrecompBlocks); + Debug.Assert(0 <= index && index < PrecompPoints); + + int off = block * PrecompPoints * 2 * X448Field.Size; + + for (int i = 0; i < PrecompPoints; ++i) + { + int mask = ((i ^ index) - 1) >> 31; + Nat.CMov(X448Field.Size, mask, precompBase, off, p.x, 0); off += X448Field.Size; + Nat.CMov(X448Field.Size, mask, precompBase, off, p.y, 0); off += X448Field.Size; + } + } + + private static PointExt[] PointPrecompVar(PointExt p, int count) + { + Debug.Assert(count > 0); + + PointExt d = PointCopy(p); + PointDouble(d); + + PointExt[] table = new PointExt[count]; + table[0] = PointCopy(p); + for (int i = 1; i < count; ++i) + { + table[i] = PointCopy(table[i - 1]); + PointAddVar(false, d, table[i]); + } + return table; + } + + private static void PointSetNeutral(PointExt p) + { + X448Field.Zero(p.x); + X448Field.One(p.y); + X448Field.One(p.z); + } + + [MethodImpl(MethodImplOptions.Synchronized)] + public static void Precompute() + { + if (precompBase != null) + { + return; + } + + PointExt p = new PointExt(); + X448Field.Copy(B_x, 0, p.x, 0); + X448Field.Copy(B_y, 0, p.y, 0); + PointExtendXY(p); + + precompBaseTable = PointPrecompVar(p, 1 << (WnafWidthBase - 2)); + + precompBase = new uint[PrecompBlocks * PrecompPoints * 2 * X448Field.Size]; + + int off = 0; + for (int b = 0; b < PrecompBlocks; ++b) + { + PointExt[] ds = new PointExt[PrecompTeeth]; + + PointExt sum = new PointExt(); + PointSetNeutral(sum); + + for (int t = 0; t < PrecompTeeth; ++t) + { + PointAddVar(true, p, sum); + PointDouble(p); + + ds[t] = PointCopy(p); + + for (int s = 1; s < PrecompSpacing; ++s) + { + PointDouble(p); + } + } + + PointExt[] points = new PointExt[PrecompPoints]; + int k = 0; + points[k++] = sum; + + for (int t = 0; t < (PrecompTeeth - 1); ++t) + { + int size = 1 << t; + for (int j = 0; j < size; ++j, ++k) + { + points[k] = PointCopy(points[k - size]); + PointAddVar(false, ds[t], points[k]); + } + } + + Debug.Assert(k == PrecompPoints); + + for (int i = 0; i < PrecompPoints; ++i) + { + PointExt q = points[i]; + // TODO[ed448] Batch inversion + X448Field.Inv(q.z, q.z); + X448Field.Mul(q.x, q.z, q.x); + X448Field.Mul(q.y, q.z, q.y); + + // X448Field.Normalize(q.x); + // X448Field.Normalize(q.y); + + X448Field.Copy(q.x, 0, precompBase, off); off += X448Field.Size; + X448Field.Copy(q.y, 0, precompBase, off); off += X448Field.Size; + } + } + + Debug.Assert(off == precompBase.Length); + } + + private static void PruneScalar(byte[] n, int nOff, byte[] r) + { + Array.Copy(n, nOff, r, 0, ScalarBytes); + + r[0] &= 0xFC; + r[ScalarBytes - 2] |= 0x80; + r[ScalarBytes - 1] &= 0x00; + } + + private static byte[] ReduceScalar(byte[] n) + { + ulong x00 = Decode32(n, 0); // x00:32/-- + ulong x01 = (Decode24(n, 4) << 4); // x01:28/-- + ulong x02 = Decode32(n, 7); // x02:32/-- + ulong x03 = (Decode24(n, 11) << 4); // x03:28/-- + ulong x04 = Decode32(n, 14); // x04:32/-- + ulong x05 = (Decode24(n, 18) << 4); // x05:28/-- + ulong x06 = Decode32(n, 21); // x06:32/-- + ulong x07 = (Decode24(n, 25) << 4); // x07:28/-- + ulong x08 = Decode32(n, 28); // x08:32/-- + ulong x09 = (Decode24(n, 32) << 4); // x09:28/-- + ulong x10 = Decode32(n, 35); // x10:32/-- + ulong x11 = (Decode24(n, 39) << 4); // x11:28/-- + ulong x12 = Decode32(n, 42); // x12:32/-- + ulong x13 = (Decode24(n, 46) << 4); // x13:28/-- + ulong x14 = Decode32(n, 49); // x14:32/-- + ulong x15 = (Decode24(n, 53) << 4); // x15:28/-- + ulong x16 = Decode32(n, 56); // x16:32/-- + ulong x17 = (Decode24(n, 60) << 4); // x17:28/-- + ulong x18 = Decode32(n, 63); // x18:32/-- + ulong x19 = (Decode24(n, 67) << 4); // x19:28/-- + ulong x20 = Decode32(n, 70); // x20:32/-- + ulong x21 = (Decode24(n, 74) << 4); // x21:28/-- + ulong x22 = Decode32(n, 77); // x22:32/-- + ulong x23 = (Decode24(n, 81) << 4); // x23:28/-- + ulong x24 = Decode32(n, 84); // x24:32/-- + ulong x25 = (Decode24(n, 88) << 4); // x25:28/-- + ulong x26 = Decode32(n, 91); // x26:32/-- + ulong x27 = (Decode24(n, 95) << 4); // x27:28/-- + ulong x28 = Decode32(n, 98); // x28:32/-- + ulong x29 = (Decode24(n, 102) << 4); // x29:28/-- + ulong x30 = Decode32(n, 105); // x30:32/-- + ulong x31 = (Decode24(n, 109) << 4); // x31:28/-- + ulong x32 = Decode16(n, 112); // x32:16/-- + + // x32 += (x31 >> 28); x31 &= M28UL; + x16 += x32 * L4_0; // x16:42/-- + x17 += x32 * L4_1; // x17:41/28 + x18 += x32 * L4_2; // x18:43/42 + x19 += x32 * L4_3; // x19:44/28 + x20 += x32 * L4_4; // x20:43/-- + x21 += x32 * L4_5; // x21:44/28 + x22 += x32 * L4_6; // x22:43/41 + x23 += x32 * L4_7; // x23:45/41 + + x31 += (x30 >> 28); x30 &= M28UL; // x31:28/--, x30:28/-- + x15 += x31 * L4_0; // x15:54/-- + x16 += x31 * L4_1; // x16:53/42 + x17 += x31 * L4_2; // x17:55/54 + x18 += x31 * L4_3; // x18:56/44 + x19 += x31 * L4_4; // x19:55/-- + x20 += x31 * L4_5; // x20:56/43 + x21 += x31 * L4_6; // x21:55/53 + x22 += x31 * L4_7; // x22:57/53 + + // x30 += (x29 >> 28); x29 &= M28UL; + x14 += x30 * L4_0; // x14:54/-- + x15 += x30 * L4_1; // x15:54/53 + x16 += x30 * L4_2; // x16:56/-- + x17 += x30 * L4_3; // x17:57/-- + x18 += x30 * L4_4; // x18:56/55 + x19 += x30 * L4_5; // x19:56/55 + x20 += x30 * L4_6; // x20:57/-- + x21 += x30 * L4_7; // x21:57/56 + + x29 += (x28 >> 28); x28 &= M28UL; // x29:28/--, x28:28/-- + x13 += x29 * L4_0; // x13:54/-- + x14 += x29 * L4_1; // x14:54/53 + x15 += x29 * L4_2; // x15:56/-- + x16 += x29 * L4_3; // x16:57/-- + x17 += x29 * L4_4; // x17:57/55 + x18 += x29 * L4_5; // x18:57/55 + x19 += x29 * L4_6; // x19:57/52 + x20 += x29 * L4_7; // x20:58/52 + + // x28 += (x27 >> 28); x27 &= M28UL; + x12 += x28 * L4_0; // x12:54/-- + x13 += x28 * L4_1; // x13:54/53 + x14 += x28 * L4_2; // x14:56/-- + x15 += x28 * L4_3; // x15:57/-- + x16 += x28 * L4_4; // x16:57/55 + x17 += x28 * L4_5; // x17:58/-- + x18 += x28 * L4_6; // x18:58/-- + x19 += x28 * L4_7; // x19:58/53 + + x27 += (x26 >> 28); x26 &= M28UL; // x27:28/--, x26:28/-- + x11 += x27 * L4_0; // x11:54/-- + x12 += x27 * L4_1; // x12:54/53 + x13 += x27 * L4_2; // x13:56/-- + x14 += x27 * L4_3; // x14:57/-- + x15 += x27 * L4_4; // x15:57/55 + x16 += x27 * L4_5; // x16:58/-- + x17 += x27 * L4_6; // x17:58/56 + x18 += x27 * L4_7; // x18:59/-- + + // x26 += (x25 >> 28); x25 &= M28UL; + x10 += x26 * L4_0; // x10:54/-- + x11 += x26 * L4_1; // x11:54/53 + x12 += x26 * L4_2; // x12:56/-- + x13 += x26 * L4_3; // x13:57/-- + x14 += x26 * L4_4; // x14:57/55 + x15 += x26 * L4_5; // x15:58/-- + x16 += x26 * L4_6; // x16:58/56 + x17 += x26 * L4_7; // x17:59/-- + + x25 += (x24 >> 28); x24 &= M28UL; // x25:28/--, x24:28/-- + x09 += x25 * L4_0; // x09:54/-- + x10 += x25 * L4_1; // x10:54/53 + x11 += x25 * L4_2; // x11:56/-- + x12 += x25 * L4_3; // x12:57/-- + x13 += x25 * L4_4; // x13:57/55 + x14 += x25 * L4_5; // x14:58/-- + x15 += x25 * L4_6; // x15:58/56 + x16 += x25 * L4_7; // x16:59/-- + + x21 += (x20 >> 28); x20 &= M28UL; // x21:58/--, x20:28/-- + x22 += (x21 >> 28); x21 &= M28UL; // x22:57/54, x21:28/-- + x23 += (x22 >> 28); x22 &= M28UL; // x23:45/42, x22:28/-- + x24 += (x23 >> 28); x23 &= M28UL; // x24:28/18, x23:28/-- + + x08 += x24 * L4_0; // x08:54/-- + x09 += x24 * L4_1; // x09:55/-- + x10 += x24 * L4_2; // x10:56/46 + x11 += x24 * L4_3; // x11:57/46 + x12 += x24 * L4_4; // x12:57/55 + x13 += x24 * L4_5; // x13:58/-- + x14 += x24 * L4_6; // x14:58/56 + x15 += x24 * L4_7; // x15:59/-- + + x07 += x23 * L4_0; // x07:54/-- + x08 += x23 * L4_1; // x08:54/53 + x09 += x23 * L4_2; // x09:56/53 + x10 += x23 * L4_3; // x10:57/46 + x11 += x23 * L4_4; // x11:57/55 + x12 += x23 * L4_5; // x12:58/-- + x13 += x23 * L4_6; // x13:58/56 + x14 += x23 * L4_7; // x14:59/-- + + x06 += x22 * L4_0; // x06:54/-- + x07 += x22 * L4_1; // x07:54/53 + x08 += x22 * L4_2; // x08:56/-- + x09 += x22 * L4_3; // x09:57/53 + x10 += x22 * L4_4; // x10:57/55 + x11 += x22 * L4_5; // x11:58/-- + x12 += x22 * L4_6; // x12:58/56 + x13 += x22 * L4_7; // x13:59/-- + + x18 += (x17 >> 28); x17 &= M28UL; // x18:59/31, x17:28/-- + x19 += (x18 >> 28); x18 &= M28UL; // x19:58/54, x18:28/-- + x20 += (x19 >> 28); x19 &= M28UL; // x20:30/29, x19:28/-- + x21 += (x20 >> 28); x20 &= M28UL; // x21:28/03, x20:28/-- + + x05 += x21 * L4_0; // x05:54/-- + x06 += x21 * L4_1; // x06:55/-- + x07 += x21 * L4_2; // x07:56/31 + x08 += x21 * L4_3; // x08:57/31 + x09 += x21 * L4_4; // x09:57/56 + x10 += x21 * L4_5; // x10:58/-- + x11 += x21 * L4_6; // x11:58/56 + x12 += x21 * L4_7; // x12:59/-- + + x04 += x20 * L4_0; // x04:54/-- + x05 += x20 * L4_1; // x05:54/53 + x06 += x20 * L4_2; // x06:56/53 + x07 += x20 * L4_3; // x07:57/31 + x08 += x20 * L4_4; // x08:57/55 + x09 += x20 * L4_5; // x09:58/-- + x10 += x20 * L4_6; // x10:58/56 + x11 += x20 * L4_7; // x11:59/-- + + x03 += x19 * L4_0; // x03:54/-- + x04 += x19 * L4_1; // x04:54/53 + x05 += x19 * L4_2; // x05:56/-- + x06 += x19 * L4_3; // x06:57/53 + x07 += x19 * L4_4; // x07:57/55 + x08 += x19 * L4_5; // x08:58/-- + x09 += x19 * L4_6; // x09:58/56 + x10 += x19 * L4_7; // x10:59/-- + + x15 += (x14 >> 28); x14 &= M28UL; // x15:59/31, x14:28/-- + x16 += (x15 >> 28); x15 &= M28UL; // x16:59/32, x15:28/-- + x17 += (x16 >> 28); x16 &= M28UL; // x17:31/29, x16:28/-- + x18 += (x17 >> 28); x17 &= M28UL; // x18:28/04, x17:28/-- + + x02 += x18 * L4_0; // x02:54/-- + x03 += x18 * L4_1; // x03:55/-- + x04 += x18 * L4_2; // x04:56/32 + x05 += x18 * L4_3; // x05:57/32 + x06 += x18 * L4_4; // x06:57/56 + x07 += x18 * L4_5; // x07:58/-- + x08 += x18 * L4_6; // x08:58/56 + x09 += x18 * L4_7; // x09:59/-- + + x01 += x17 * L4_0; // x01:54/-- + x02 += x17 * L4_1; // x02:54/53 + x03 += x17 * L4_2; // x03:56/53 + x04 += x17 * L4_3; // x04:57/32 + x05 += x17 * L4_4; // x05:57/55 + x06 += x17 * L4_5; // x06:58/-- + x07 += x17 * L4_6; // x07:58/56 + x08 += x17 * L4_7; // x08:59/-- + + x16 *= 4; + x16 += (x15 >> 26); x15 &= M26UL; + x16 += 1; // x16:30/01 + + x00 += x16 * L_0; + x01 += x16 * L_1; + x02 += x16 * L_2; + x03 += x16 * L_3; + x04 += x16 * L_4; + x05 += x16 * L_5; + x06 += x16 * L_6; + x07 += x16 * L_7; + + x01 += (x00 >> 28); x00 &= M28UL; + x02 += (x01 >> 28); x01 &= M28UL; + x03 += (x02 >> 28); x02 &= M28UL; + x04 += (x03 >> 28); x03 &= M28UL; + x05 += (x04 >> 28); x04 &= M28UL; + x06 += (x05 >> 28); x05 &= M28UL; + x07 += (x06 >> 28); x06 &= M28UL; + x08 += (x07 >> 28); x07 &= M28UL; + x09 += (x08 >> 28); x08 &= M28UL; + x10 += (x09 >> 28); x09 &= M28UL; + x11 += (x10 >> 28); x10 &= M28UL; + x12 += (x11 >> 28); x11 &= M28UL; + x13 += (x12 >> 28); x12 &= M28UL; + x14 += (x13 >> 28); x13 &= M28UL; + x15 += (x14 >> 28); x14 &= M28UL; + x16 = (x15 >> 26); x15 &= M26UL; + + x16 -= 1; + + Debug.Assert(x16 == 0UL || x16 == ulong.MaxValue); + + x00 -= x16 & L_0; + x01 -= x16 & L_1; + x02 -= x16 & L_2; + x03 -= x16 & L_3; + x04 -= x16 & L_4; + x05 -= x16 & L_5; + x06 -= x16 & L_6; + x07 -= x16 & L_7; + + x01 += (ulong)((long)x00 >> 28); x00 &= M28UL; + x02 += (ulong)((long)x01 >> 28); x01 &= M28UL; + x03 += (ulong)((long)x02 >> 28); x02 &= M28UL; + x04 += (ulong)((long)x03 >> 28); x03 &= M28UL; + x05 += (ulong)((long)x04 >> 28); x04 &= M28UL; + x06 += (ulong)((long)x05 >> 28); x05 &= M28UL; + x07 += (ulong)((long)x06 >> 28); x06 &= M28UL; + x08 += (ulong)((long)x07 >> 28); x07 &= M28UL; + x09 += (ulong)((long)x08 >> 28); x08 &= M28UL; + x10 += (ulong)((long)x09 >> 28); x09 &= M28UL; + x11 += (ulong)((long)x10 >> 28); x10 &= M28UL; + x12 += (ulong)((long)x11 >> 28); x11 &= M28UL; + x13 += (ulong)((long)x12 >> 28); x12 &= M28UL; + x14 += (ulong)((long)x13 >> 28); x13 &= M28UL; + x15 += (ulong)((long)x14 >> 28); x14 &= M28UL; + + Debug.Assert(x15 >> 26 == 0UL); + + byte[] r = new byte[ScalarBytes]; + Encode56(x00 | (x01 << 28), r, 0); + Encode56(x02 | (x03 << 28), r, 7); + Encode56(x04 | (x05 << 28), r, 14); + Encode56(x06 | (x07 << 28), r, 21); + Encode56(x08 | (x09 << 28), r, 28); + Encode56(x10 | (x11 << 28), r, 35); + Encode56(x12 | (x13 << 28), r, 42); + Encode56(x14 | (x15 << 28), r, 49); + // r[ScalarBytes - 1] = 0; + return r; + } + + private static void ScalarMultBase(byte[] k, PointExt r) + { + Precompute(); + + PointSetNeutral(r); + + uint[] n = new uint[ScalarUints + 1]; + DecodeScalar(k, 0, n); + + // Recode the scalar into signed-digit form + { + n[ScalarUints] = 4U + Nat.CAdd(ScalarUints, ~(int)n[0] & 1, n, L, n); + uint c = Nat.ShiftDownBit(n.Length, n, 0); + Debug.Assert(c == (1U << 31)); + } + + PointPrecomp p = new PointPrecomp(); + + int cOff = PrecompSpacing - 1; + for (;;) + { + int tPos = cOff; + + for (int b = 0; b < PrecompBlocks; ++b) + { + uint w = 0; + for (int t = 0; t < PrecompTeeth; ++t) + { + uint tBit = (n[tPos >> 5] >> (tPos & 0x1F)) & 1U; + w |= tBit << t; + tPos += PrecompSpacing; + } + + int sign = (int)(w >> (PrecompTeeth - 1)) & 1; + int abs = ((int)w ^ -sign) & PrecompMask; + + Debug.Assert(sign == 0 || sign == 1); + Debug.Assert(0 <= abs && abs < PrecompPoints); + + PointLookup(b, abs, p); + + X448Field.CNegate(sign, p.x); + + PointAddPrecomp(p, r); + } + + if (--cOff < 0) + { + break; + } + + PointDouble(r); + } + } + + private static void ScalarMultBaseEncoded(byte[] k, byte[] r, int rOff) + { + PointExt p = new PointExt(); + ScalarMultBase(k, p); + EncodePoint(p, r, rOff); + } + + private static void ScalarMultStraussVar(uint[] nb, uint[] np, PointExt p, PointExt r) + { + Precompute(); + + int width = 5; + + sbyte[] ws_b = GetWnaf(nb, WnafWidthBase); + sbyte[] ws_p = GetWnaf(np, width); + + PointExt[] tp = PointPrecompVar(p, 1 << (width - 2)); + + PointSetNeutral(r); + + int bit = 447; + while (bit > 0 && (ws_b[bit] | ws_p[bit]) == 0) + { + --bit; + } + + for (;;) + { + int wb = ws_b[bit]; + if (wb != 0) + { + int sign = wb >> 31; + int index = (wb ^ sign) >> 1; + + PointAddVar((sign != 0), precompBaseTable[index], r); + } + + int wp = ws_p[bit]; + if (wp != 0) + { + int sign = wp >> 31; + int index = (wp ^ sign) >> 1; + + PointAddVar((sign != 0), tp[index], r); + } + + if (--bit < 0) + { + break; + } + + PointDouble(r); + } + } + + public static void Sign(byte[] sk, int skOff, byte[] ctx, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) + { + if (!CheckContextVar(ctx)) + { + throw new ArgumentException("ctx"); + } + + ShakeDigest d = new ShakeDigest(256); + byte[] h = new byte[ScalarBytes * 2]; + + d.BlockUpdate(sk, skOff, SecretKeySize); + d.DoFinal(h, 0, h.Length); + + byte[] s = new byte[ScalarBytes]; + PruneScalar(h, 0, s); + + byte[] pk = new byte[PointBytes]; + ScalarMultBaseEncoded(s, pk, 0); + + ImplSign(d, h, s, pk, 0, ctx, m, mOff, mLen, sig, sigOff); + } + + public static void Sign(byte[] sk, int skOff, byte[] pk, int pkOff, byte[] ctx, byte[] m, int mOff, int mLen, byte[] sig, int sigOff) + { + if (!CheckContextVar(ctx)) + { + throw new ArgumentException("ctx"); + } + + ShakeDigest d = new ShakeDigest(256); + byte[] h = new byte[ScalarBytes * 2]; + + d.BlockUpdate(sk, skOff, SecretKeySize); + d.DoFinal(h, 0, h.Length); + + byte[] s = new byte[ScalarBytes]; + PruneScalar(h, 0, s); + + ImplSign(d, h, s, pk, pkOff, ctx, m, mOff, mLen, sig, sigOff); + } + + public static bool Verify(byte[] sig, int sigOff, byte[] pk, int pkOff, byte[] ctx, byte[] m, int mOff, int mLen) + { + if (!CheckContextVar(ctx)) + { + throw new ArgumentException("ctx"); + } + + byte[] R = Arrays.CopyOfRange(sig, sigOff, sigOff + PointBytes); + byte[] S = Arrays.CopyOfRange(sig, sigOff + PointBytes, sigOff + SignatureSize); + + if (!CheckPointVar(R)) + { + return false; + } + if (!CheckScalarVar(S)) + { + return false; + } + + PointExt pA = new PointExt(); + if (!DecodePointVar(pk, pkOff, true, pA)) + { + return false; + } + + byte phflag = 0x00; + + ShakeDigest d = new ShakeDigest(256); + byte[] h = new byte[ScalarBytes * 2]; + + Dom4(d, phflag, ctx); + d.BlockUpdate(R, 0, PointBytes); + d.BlockUpdate(pk, pkOff, PointBytes); + d.BlockUpdate(m, mOff, mLen); + d.DoFinal(h, 0, h.Length); + + byte[] k = ReduceScalar(h); + + uint[] nS = new uint[ScalarUints]; + DecodeScalar(S, 0, nS); + + uint[] nA = new uint[ScalarUints]; + DecodeScalar(k, 0, nA); + + PointExt pR = new PointExt(); + ScalarMultStraussVar(nS, nA, pA, pR); + + byte[] check = new byte[PointBytes]; + EncodePoint(pR, check, 0); + + return Arrays.AreEqual(check, R); + } + } +} diff --git a/crypto/src/math/raw/Interleave.cs b/crypto/src/math/raw/Interleave.cs index d21840644..591ba3f15 100644 --- a/crypto/src/math/raw/Interleave.cs +++ b/crypto/src/math/raw/Interleave.cs @@ -6,6 +6,7 @@ namespace Org.BouncyCastle.Math.Raw { private const ulong M32 = 0x55555555UL; private const ulong M64 = 0x5555555555555555UL; + private const ulong M64R = 0xAAAAAAAAAAAAAAAAUL; /* * This expands 8 bit indices into 16 bit contents (high bit 14), by inserting 0s between bits. @@ -92,6 +93,65 @@ namespace Org.BouncyCastle.Math.Raw z[zOff + 1] = (x >> 1) & M64; } + internal static void Expand64To128Rev(ulong x, ulong[] z, int zOff) + { + // "shuffle" low half to even bits and high half to odd bits + ulong t; + t = (x ^ (x >> 16)) & 0x00000000FFFF0000UL; x ^= (t ^ (t << 16)); + t = (x ^ (x >> 8)) & 0x0000FF000000FF00UL; x ^= (t ^ (t << 8)); + t = (x ^ (x >> 4)) & 0x00F000F000F000F0UL; x ^= (t ^ (t << 4)); + t = (x ^ (x >> 2)) & 0x0C0C0C0C0C0C0C0CUL; x ^= (t ^ (t << 2)); + t = (x ^ (x >> 1)) & 0x2222222222222222UL; x ^= (t ^ (t << 1)); + + z[zOff] = (x ) & M64R; + z[zOff + 1] = (x << 1) & M64R; + } + + internal static uint Shuffle(uint x) + { + // "shuffle" low half to even bits and high half to odd bits + uint t; + t = (x ^ (x >> 8)) & 0x0000FF00U; x ^= (t ^ (t << 8)); + t = (x ^ (x >> 4)) & 0x00F000F0U; x ^= (t ^ (t << 4)); + t = (x ^ (x >> 2)) & 0x0C0C0C0CU; x ^= (t ^ (t << 2)); + t = (x ^ (x >> 1)) & 0x22222222U; x ^= (t ^ (t << 1)); + return x; + } + + internal static ulong Shuffle(ulong x) + { + // "shuffle" low half to even bits and high half to odd bits + ulong t; + t = (x ^ (x >> 16)) & 0x00000000FFFF0000UL; x ^= (t ^ (t << 16)); + t = (x ^ (x >> 8)) & 0x0000FF000000FF00UL; x ^= (t ^ (t << 8)); + t = (x ^ (x >> 4)) & 0x00F000F000F000F0UL; x ^= (t ^ (t << 4)); + t = (x ^ (x >> 2)) & 0x0C0C0C0C0C0C0C0CUL; x ^= (t ^ (t << 2)); + t = (x ^ (x >> 1)) & 0x2222222222222222UL; x ^= (t ^ (t << 1)); + return x; + } + + internal static uint Shuffle2(uint x) + { + // "shuffle" (twice) low half to even bits and high half to odd bits + uint t; + t = (x ^ (x >> 7)) & 0x00AA00AAU; x ^= (t ^ (t << 7)); + t = (x ^ (x >> 14)) & 0x0000CCCCU; x ^= (t ^ (t << 14)); + t = (x ^ (x >> 4)) & 0x00F000F0U; x ^= (t ^ (t << 4)); + t = (x ^ (x >> 8)) & 0x0000FF00U; x ^= (t ^ (t << 8)); + return x; + } + + internal static uint Unshuffle(uint x) + { + // "unshuffle" even bits to low half and odd bits to high half + uint t; + t = (x ^ (x >> 1)) & 0x22222222U; x ^= (t ^ (t << 1)); + t = (x ^ (x >> 2)) & 0x0C0C0C0CU; x ^= (t ^ (t << 2)); + t = (x ^ (x >> 4)) & 0x00F000F0U; x ^= (t ^ (t << 4)); + t = (x ^ (x >> 8)) & 0x0000FF00U; x ^= (t ^ (t << 8)); + return x; + } + internal static ulong Unshuffle(ulong x) { // "unshuffle" even bits to low half and odd bits to high half @@ -103,5 +163,16 @@ namespace Org.BouncyCastle.Math.Raw t = (x ^ (x >> 16)) & 0x00000000FFFF0000UL; x ^= (t ^ (t << 16)); return x; } + + internal static uint Unshuffle2(uint x) + { + // "unshuffle" (twice) even bits to low half and odd bits to high half + uint t; + t = (x ^ (x >> 8)) & 0x0000FF00U; x ^= (t ^ (t << 8)); + t = (x ^ (x >> 4)) & 0x00F000F0U; x ^= (t ^ (t << 4)); + t = (x ^ (x >> 14)) & 0x0000CCCCU; x ^= (t ^ (t << 14)); + t = (x ^ (x >> 7)) & 0x00AA00AAU; x ^= (t ^ (t << 7)); + return x; + } } } diff --git a/crypto/src/math/raw/Nat.cs b/crypto/src/math/raw/Nat.cs index cf6516c61..7ca60278a 100644 --- a/crypto/src/math/raw/Nat.cs +++ b/crypto/src/math/raw/Nat.cs @@ -195,6 +195,64 @@ namespace Org.BouncyCastle.Math.Raw return c == 0 ? 0 : IncAt(len, z, zOff, 1); } + public static uint CAdd(int len, int mask, uint[] x, uint[] y, uint[] z) + { + uint MASK = (uint)-(mask & 1); + + ulong c = 0; + for (int i = 0; i < len; ++i) + { + c += (ulong)x[i] + (y[i] & MASK); + z[i] = (uint)c; + c >>= 32; + } + return (uint)c; + } + + public static void CMov(int len, int mask, uint[] x, int xOff, uint[] z, int zOff) + { + uint MASK = (uint)-(mask & 1); + + for (int i = 0; i < len; ++i) + { + uint z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; + z_i ^= (diff & MASK); + z[zOff + i] = z_i; + } + + //uint half = 0x55555555U, rest = half << (-(int)MASK); + + //for (int i = 0; i < len; ++i) + //{ + // uint z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; + // z_i ^= (diff & half); + // z_i ^= (diff & rest); + // z[zOff + i] = z_i; + //} + } + + public static void CMov(int len, int mask, int[] x, int xOff, int[] z, int zOff) + { + mask = -(mask & 1); + + for (int i = 0; i < len; ++i) + { + int z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; + z_i ^= (diff & mask); + z[zOff + i] = z_i; + } + + //int half = 0x55555555, rest = half << (-mask); + + //for (int i = 0; i < len; ++i) + //{ + // int z_i = z[zOff + i], diff = z_i ^ x[xOff + i]; + // z_i ^= (diff & half); + // z_i ^= (diff & rest); + // z[zOff + i] = z_i; + //} + } + public static void Copy(int len, uint[] x, uint[] z) { Array.Copy(x, 0, z, 0, len); @@ -448,6 +506,33 @@ namespace Org.BouncyCastle.Math.Raw } } + public static uint MulAddTo(int len, uint[] x, uint[] y, uint[] zz) + { + ulong zc = 0; + for (int i = 0; i < len; ++i) + { + ulong c = MulWordAddTo(len, x[i], y, 0, zz, i) & M; + c += zc + (zz[i + len] & M); + zz[i + len] = (uint)c; + zc = c >> 32; + } + return (uint)zc; + } + + public static uint MulAddTo(int len, uint[] x, int xOff, uint[] y, int yOff, uint[] zz, int zzOff) + { + ulong zc = 0; + for (int i = 0; i < len; ++i) + { + ulong c = MulWordAddTo(len, x[xOff + i], y, yOff, zz, zzOff) & M; + c += zc + (zz[zzOff + len] & M); + zz[zzOff + len] = (uint)c; + zc = c >> 32; + ++zzOff; + } + return (uint)zc; + } + public static uint Mul31BothAdd(int len, uint a, uint[] x, uint b, uint[] y, uint[] z, int zOff) { ulong c = 0, aVal = (ulong)a, bVal = (ulong)b; diff --git a/crypto/src/openpgp/PgpUtilities.cs b/crypto/src/openpgp/PgpUtilities.cs index 5ea2907e8..039aa5893 100644 --- a/crypto/src/openpgp/PgpUtilities.cs +++ b/crypto/src/openpgp/PgpUtilities.cs @@ -356,7 +356,7 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp { PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream pOut = lData.Open(output, fileType, file.Name, file.Length, file.LastWriteTime); - PipeFileContents(file, pOut, 4096); + PipeFileContents(file, pOut, 32768); } /// <summary>Write out the passed in file as a literal data packet in partial packet format.</summary> @@ -376,15 +376,22 @@ namespace Org.BouncyCastle.Bcpg.OpenPgp FileStream inputStream = file.OpenRead(); byte[] buf = new byte[bufSize]; - int len; - while ((len = inputStream.Read(buf, 0, buf.Length)) > 0) + try { - pOut.Write(buf, 0, len); + int len; + while ((len = inputStream.Read(buf, 0, buf.Length)) > 0) + { + pOut.Write(buf, 0, len); + } } + finally + { + Array.Clear(buf, 0, buf.Length); - Platform.Dispose(pOut); - Platform.Dispose(inputStream); - } + Platform.Dispose(pOut); + Platform.Dispose(inputStream); + } + } #endif private const int ReadAhead = 60; diff --git a/crypto/test/src/crypto/test/ECGOST3410Test.cs b/crypto/test/src/crypto/test/ECGOST3410Test.cs index 5efa75169..fa79e58d9 100644 --- a/crypto/test/src/crypto/test/ECGOST3410Test.cs +++ b/crypto/test/src/crypto/test/ECGOST3410Test.cs @@ -56,7 +56,7 @@ namespace Org.BouncyCastle.Crypto.Tests curve.CreatePoint( new BigInteger("2"), // x new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), // y - mod_q); + mod_q, BigInteger.One); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECGOST3410", @@ -127,7 +127,7 @@ namespace Org.BouncyCastle.Crypto.Tests curve.CreatePoint( new BigInteger("2"), // x new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), // y - mod_q); + mod_q, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters( @@ -184,7 +184,7 @@ namespace Org.BouncyCastle.Crypto.Tests curve.CreatePoint( new BigInteger("1"), // x new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612")), // y - mod_q); + mod_q, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator("ECGOST3410"); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters( @@ -234,7 +234,7 @@ namespace Org.BouncyCastle.Crypto.Tests curve.CreatePoint( new BigInteger("1"), // x new BigInteger("28792665814854611296992347458380284135028636778229113005756334730996303888124")), // y - mod_q); + mod_q, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator("ECGOST3410"); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters( @@ -284,7 +284,7 @@ namespace Org.BouncyCastle.Crypto.Tests curve.CreatePoint( new BigInteger("0"), // x new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247")), // y - mod_q); + mod_q, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator("ECGOST3410"); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters( diff --git a/crypto/test/src/crypto/test/ECIESTest.cs b/crypto/test/src/crypto/test/ECIESTest.cs index f17e6957a..4957e7e27 100644 --- a/crypto/test/src/crypto/test/ECIESTest.cs +++ b/crypto/test/src/crypto/test/ECIESTest.cs @@ -46,9 +46,9 @@ namespace Org.BouncyCastle.Crypto.Tests n, BigInteger.One); ECDomainParameters parameters = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G - n); + curve, + curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G + n, BigInteger.One); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDH", @@ -220,9 +220,9 @@ namespace Org.BouncyCastle.Crypto.Tests n, BigInteger.One); ECDomainParameters parameters = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G - n); + curve, + curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G + n, BigInteger.One); ECKeyPairGenerator eGen = new ECKeyPairGenerator(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(parameters, new SecureRandom()); diff --git a/crypto/test/src/crypto/test/ECNRTest.cs b/crypto/test/src/crypto/test/ECNRTest.cs index 180b33560..ab4800221 100644 --- a/crypto/test/src/crypto/test/ECNRTest.cs +++ b/crypto/test/src/crypto/test/ECNRTest.cs @@ -49,7 +49,7 @@ namespace Org.BouncyCastle.Crypto.Tests ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - n); + n, BigInteger.One); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d diff --git a/crypto/test/src/crypto/test/ECTest.cs b/crypto/test/src/crypto/test/ECTest.cs index 980d04d6c..f4dd4dce2 100644 --- a/crypto/test/src/crypto/test/ECTest.cs +++ b/crypto/test/src/crypto/test/ECTest.cs @@ -5,6 +5,7 @@ using NUnit.Framework; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Asn1.X9; +using Org.BouncyCastle.Crypto.EC; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Security; @@ -52,7 +53,7 @@ namespace Org.BouncyCastle.Crypto.Tests ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G - n); + n, BigInteger.One); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", @@ -98,12 +99,8 @@ namespace Org.BouncyCastle.Crypto.Tests [Test] public void TestDecode() { - FpCurve curve = new FpCurve( - new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q - new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a - new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b - - ECPoint p = curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")).Normalize(); + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime192v1"); + ECPoint p = x9.G; if (!p.AffineXCoord.ToBigInteger().Equals(new BigInteger("188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", 16))) { @@ -115,7 +112,7 @@ namespace Org.BouncyCastle.Crypto.Tests Fail("y uncompressed incorrectly"); } - byte[] encoding = p.GetEncoded(); + byte[] encoding = p.GetEncoded(true); if (!AreEqual(encoding, Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012"))) { @@ -149,7 +146,7 @@ namespace Org.BouncyCastle.Crypto.Tests ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - n); + n, BigInteger.One); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", @@ -651,7 +648,7 @@ namespace Org.BouncyCastle.Crypto.Tests ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - n); + n, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters( @@ -683,7 +680,7 @@ namespace Org.BouncyCastle.Crypto.Tests * Basic Key Agreement Test */ [Test] - public void TestECBasicAgreementTest() + public void TestECDHBasicAgreement() { SecureRandom random = new SecureRandom(); @@ -698,7 +695,7 @@ namespace Org.BouncyCastle.Crypto.Tests ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - n); + n, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator(); ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, random); @@ -744,6 +741,35 @@ namespace Org.BouncyCastle.Crypto.Tests } [Test] + public void TestECDHBasicAgreementCofactor() + { + SecureRandom random = new SecureRandom(); + + X9ECParameters x9 = CustomNamedCurves.GetByName("curve25519"); + ECDomainParameters ec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); + + ECKeyPairGenerator kpg = new ECKeyPairGenerator(); + kpg.Init(new ECKeyGenerationParameters(ec, random)); + + AsymmetricCipherKeyPair p1 = kpg.GenerateKeyPair(); + AsymmetricCipherKeyPair p2 = kpg.GenerateKeyPair(); + + IBasicAgreement e1 = new ECDHBasicAgreement(); + IBasicAgreement e2 = new ECDHBasicAgreement(); + + e1.Init(p1.Private); + e2.Init(p2.Private); + + BigInteger k1 = e1.CalculateAgreement(p2.Public); + BigInteger k2 = e2.CalculateAgreement(p1.Public); + + if (!k1.Equals(k2)) + { + Fail("calculated agreement test failed"); + } + } + + [Test] public void TestECMqvTestVector1() { // Test Vector from GEC-2 @@ -843,7 +869,7 @@ namespace Org.BouncyCastle.Crypto.Tests ECDomainParameters parameters = new ECDomainParameters( curve, curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - n); + n, BigInteger.One); ECKeyPairGenerator pGen = new ECKeyPairGenerator(); @@ -909,7 +935,8 @@ namespace Org.BouncyCastle.Crypto.Tests TestECDsa191bitBinary(); TestECDsa239bitBinary(); TestECDsaKeyGenTest(); - TestECBasicAgreementTest(); + TestECDHBasicAgreement(); + TestECDHBasicAgreementCofactor(); TestECDsaP224Sha224(); TestECDsaP224OneByteOver(); diff --git a/crypto/test/src/crypto/test/SM2EngineTest.cs b/crypto/test/src/crypto/test/SM2EngineTest.cs index cc9440e86..f961b0acb 100644 --- a/crypto/test/src/crypto/test/SM2EngineTest.cs +++ b/crypto/test/src/crypto/test/SM2EngineTest.cs @@ -28,10 +28,11 @@ namespace Org.BouncyCastle.Crypto.Tests BigInteger SM2_ECC_A = new BigInteger("787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", 16); BigInteger SM2_ECC_B = new BigInteger("63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", 16); BigInteger SM2_ECC_N = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", 16); + BigInteger SM2_ECC_H = BigInteger.One; BigInteger SM2_ECC_GX = new BigInteger("421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", 16); BigInteger SM2_ECC_GY = new BigInteger("0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", 16); - ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B); + ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); @@ -104,11 +105,11 @@ namespace Org.BouncyCastle.Crypto.Tests BigInteger SM2_ECC_A = new BigInteger("00", 16); BigInteger SM2_ECC_B = new BigInteger("E78BCD09746C202378A7E72B12BCE00266B9627ECB0B5A25367AD1AD4CC6242B", 16); BigInteger SM2_ECC_N = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBC972CF7E6B6F900945B3C6A0CF6161D", 16); + BigInteger SM2_ECC_H = BigInteger.ValueOf(4); BigInteger SM2_ECC_GX = new BigInteger("00CDB9CA7F1E6B0441F658343F4B10297C0EF9B6491082400A62E7A7485735FADD", 16); BigInteger SM2_ECC_GY = new BigInteger("013DE74DA65951C4D76DC89220D5F7777A611B1C38BAE260B175951DC8060C2B3E", 16); - BigInteger SM2_ECC_H = BigInteger.ValueOf(4); - ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B); + ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N, SM2_ECC_H); diff --git a/crypto/test/src/crypto/test/SM2KeyExchangeTest.cs b/crypto/test/src/crypto/test/SM2KeyExchangeTest.cs index 41993218c..6308383a6 100644 --- a/crypto/test/src/crypto/test/SM2KeyExchangeTest.cs +++ b/crypto/test/src/crypto/test/SM2KeyExchangeTest.cs @@ -30,10 +30,11 @@ namespace Org.BouncyCastle.Crypto.Tests BigInteger SM2_ECC_A = new BigInteger("787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", 16); BigInteger SM2_ECC_B = new BigInteger("63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", 16); BigInteger SM2_ECC_N = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", 16); + BigInteger SM2_ECC_H = BigInteger.One; BigInteger SM2_ECC_GX = new BigInteger("421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", 16); BigInteger SM2_ECC_GY = new BigInteger("0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", 16); - ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B); + ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); @@ -119,11 +120,11 @@ namespace Org.BouncyCastle.Crypto.Tests BigInteger SM2_ECC_A = new BigInteger("00", 16); BigInteger SM2_ECC_B = new BigInteger("E78BCD09746C202378A7E72B12BCE00266B9627ECB0B5A25367AD1AD4CC6242B", 16); BigInteger SM2_ECC_N = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBC972CF7E6B6F900945B3C6A0CF6161D", 16); + BigInteger SM2_ECC_H = BigInteger.ValueOf(4); BigInteger SM2_ECC_GX = new BigInteger("00CDB9CA7F1E6B0441F658343F4B10297C0EF9B6491082400A62E7A7485735FADD", 16); BigInteger SM2_ECC_GY = new BigInteger("013DE74DA65951C4D76DC89220D5F7777A611B1C38BAE260B175951DC8060C2B3E", 16); - BigInteger SM2_ECC_H = BigInteger.ValueOf(4); - ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B); + ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N, SM2_ECC_H); diff --git a/crypto/test/src/crypto/test/SM2SignerTest.cs b/crypto/test/src/crypto/test/SM2SignerTest.cs index 795fb6323..a9e6c48e5 100644 --- a/crypto/test/src/crypto/test/SM2SignerTest.cs +++ b/crypto/test/src/crypto/test/SM2SignerTest.cs @@ -29,10 +29,11 @@ namespace Org.BouncyCastle.Crypto.Tests BigInteger SM2_ECC_A = new BigInteger("787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498", 16); BigInteger SM2_ECC_B = new BigInteger("63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A", 16); BigInteger SM2_ECC_N = new BigInteger("8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7", 16); + BigInteger SM2_ECC_H = BigInteger.ValueOf(4); BigInteger SM2_ECC_GX = new BigInteger("421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D", 16); BigInteger SM2_ECC_GY = new BigInteger("0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2", 16); - ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B); + ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); @@ -76,10 +77,11 @@ namespace Org.BouncyCastle.Crypto.Tests BigInteger SM2_ECC_A = new BigInteger("00", 16); BigInteger SM2_ECC_B = new BigInteger("E78BCD09746C202378A7E72B12BCE00266B9627ECB0B5A25367AD1AD4CC6242B", 16); BigInteger SM2_ECC_N = new BigInteger("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBC972CF7E6B6F900945B3C6A0CF6161D", 16); + BigInteger SM2_ECC_H = BigInteger.ValueOf(4); BigInteger SM2_ECC_GX = new BigInteger("00CDB9CA7F1E6B0441F658343F4B10297C0EF9B6491082400A62E7A7485735FADD", 16); BigInteger SM2_ECC_GY = new BigInteger("013DE74DA65951C4D76DC89220D5F7777A611B1C38BAE260B175951DC8060C2B3E", 16); - ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B); + ECCurve curve = new F2mCurve(257, 12, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H); ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY); ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N); diff --git a/crypto/test/src/math/ec/rfc8032/test/Ed25519Test.cs b/crypto/test/src/math/ec/rfc8032/test/Ed25519Test.cs new file mode 100644 index 000000000..43ea23988 --- /dev/null +++ b/crypto/test/src/math/ec/rfc8032/test/Ed25519Test.cs @@ -0,0 +1,231 @@ +using System; + +using NUnit.Framework; + +using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; +using Org.BouncyCastle.Utilities.Encoders; + +namespace Org.BouncyCastle.Math.EC.Rfc8032.Tests +{ + [TestFixture] + public class Ed25519Test + { + private static readonly SecureRandom Random = new SecureRandom(); + + [SetUp] + public void SetUp() + { + Ed25519.Precompute(); + } + + [Test] + public void TestEd25519Consistency() + { + byte[] sk = new byte[Ed25519.SecretKeySize]; + byte[] pk = new byte[Ed25519.PublicKeySize]; + byte[] m = new byte[255]; + byte[] sig1 = new byte[Ed25519.SignatureSize]; + byte[] sig2 = new byte[Ed25519.SignatureSize]; + + Random.NextBytes(m); + + for (int i = 0; i < 10; ++i) + { + Random.NextBytes(sk); + Ed25519.GeneratePublicKey(sk, 0, pk, 0); + + int mLen = Random.Next() & 255; + + Ed25519.Sign(sk, 0, m, 0, mLen, sig1, 0); + Ed25519.Sign(sk, 0, pk, 0, m, 0, mLen, sig2, 0); + + Assert.IsTrue(Arrays.AreEqual(sig1, sig2), "Consistent signatures #" + i); + + bool shouldVerify = Ed25519.Verify(sig1, 0, pk, 0, m, 0, mLen); + + Assert.IsTrue(shouldVerify, "Consistent sign/verify #" + i); + + sig1[Ed25519.PublicKeySize - 1] ^= 0x80; + bool shouldNotVerify = Ed25519.Verify(sig1, 0, pk, 0, m, 0, mLen); + + Assert.IsFalse(shouldNotVerify, "Consistent verification failure #" + i); + } + } + + [Test] + public void TestEd25519Vector1() + { + CheckEd25519Vector( + ("9d61b19deffd5a60ba844af492ec2cc4" + + "4449c5697b326919703bac031cae7f60"), + ("d75a980182b10ab7d54bfed3c964073a" + + "0ee172f3daa62325af021a68f707511a"), + "", + ("e5564300c360ac729086e2cc806e828a" + + "84877f1eb8e5d974d873e06522490155" + + "5fb8821590a33bacc61e39701cf9b46b" + + "d25bf5f0595bbe24655141438e7a100b"), + "Ed25519 Vector #1"); + } + + [Test] + public void TestEd25519Vector2() + { + CheckEd25519Vector( + ("4ccd089b28ff96da9db6c346ec114e0f" + + "5b8a319f35aba624da8cf6ed4fb8a6fb"), + ("3d4017c3e843895a92b70aa74d1b7ebc" + + "9c982ccf2ec4968cc0cd55f12af4660c"), + "72", + ("92a009a9f0d4cab8720e820b5f642540" + + "a2b27b5416503f8fb3762223ebdb69da" + + "085ac1e43e15996e458f3613d0f11d8c" + + "387b2eaeb4302aeeb00d291612bb0c00"), + "Ed25519 Vector #2"); + } + + [Test] + public void TestEd25519Vector3() + { + CheckEd25519Vector( + ("c5aa8df43f9f837bedb7442f31dcb7b1" + + "66d38535076f094b85ce3a2e0b4458f7"), + ("fc51cd8e6218a1a38da47ed00230f058" + + "0816ed13ba3303ac5deb911548908025"), + "af82", + ("6291d657deec24024827e69c3abe01a3" + + "0ce548a284743a445e3680d7db5ac3ac" + + "18ff9b538d16f290ae67f760984dc659" + + "4a7c15e9716ed28dc027beceea1ec40a"), + "Ed25519 Vector #3"); + } + + [Test] + public void TestEd25519Vector1023() + { + string m = + "08b8b2b733424243760fe426a4b54908" + + "632110a66c2f6591eabd3345e3e4eb98" + + "fa6e264bf09efe12ee50f8f54e9f77b1" + + "e355f6c50544e23fb1433ddf73be84d8" + + "79de7c0046dc4996d9e773f4bc9efe57" + + "38829adb26c81b37c93a1b270b20329d" + + "658675fc6ea534e0810a4432826bf58c" + + "941efb65d57a338bbd2e26640f89ffbc" + + "1a858efcb8550ee3a5e1998bd177e93a" + + "7363c344fe6b199ee5d02e82d522c4fe" + + "ba15452f80288a821a579116ec6dad2b" + + "3b310da903401aa62100ab5d1a36553e" + + "06203b33890cc9b832f79ef80560ccb9" + + "a39ce767967ed628c6ad573cb116dbef" + + "efd75499da96bd68a8a97b928a8bbc10" + + "3b6621fcde2beca1231d206be6cd9ec7" + + "aff6f6c94fcd7204ed3455c68c83f4a4" + + "1da4af2b74ef5c53f1d8ac70bdcb7ed1" + + "85ce81bd84359d44254d95629e9855a9" + + "4a7c1958d1f8ada5d0532ed8a5aa3fb2" + + "d17ba70eb6248e594e1a2297acbbb39d" + + "502f1a8c6eb6f1ce22b3de1a1f40cc24" + + "554119a831a9aad6079cad88425de6bd" + + "e1a9187ebb6092cf67bf2b13fd65f270" + + "88d78b7e883c8759d2c4f5c65adb7553" + + "878ad575f9fad878e80a0c9ba63bcbcc" + + "2732e69485bbc9c90bfbd62481d9089b" + + "eccf80cfe2df16a2cf65bd92dd597b07" + + "07e0917af48bbb75fed413d238f5555a" + + "7a569d80c3414a8d0859dc65a46128ba" + + "b27af87a71314f318c782b23ebfe808b" + + "82b0ce26401d2e22f04d83d1255dc51a" + + "ddd3b75a2b1ae0784504df543af8969b" + + "e3ea7082ff7fc9888c144da2af58429e" + + "c96031dbcad3dad9af0dcbaaaf268cb8" + + "fcffead94f3c7ca495e056a9b47acdb7" + + "51fb73e666c6c655ade8297297d07ad1" + + "ba5e43f1bca32301651339e22904cc8c" + + "42f58c30c04aafdb038dda0847dd988d" + + "cda6f3bfd15c4b4c4525004aa06eeff8" + + "ca61783aacec57fb3d1f92b0fe2fd1a8" + + "5f6724517b65e614ad6808d6f6ee34df" + + "f7310fdc82aebfd904b01e1dc54b2927" + + "094b2db68d6f903b68401adebf5a7e08" + + "d78ff4ef5d63653a65040cf9bfd4aca7" + + "984a74d37145986780fc0b16ac451649" + + "de6188a7dbdf191f64b5fc5e2ab47b57" + + "f7f7276cd419c17a3ca8e1b939ae49e4" + + "88acba6b965610b5480109c8b17b80e1" + + "b7b750dfc7598d5d5011fd2dcc5600a3" + + "2ef5b52a1ecc820e308aa342721aac09" + + "43bf6686b64b2579376504ccc493d97e" + + "6aed3fb0f9cd71a43dd497f01f17c0e2" + + "cb3797aa2a2f256656168e6c496afc5f" + + "b93246f6b1116398a346f1a641f3b041" + + "e989f7914f90cc2c7fff357876e506b5" + + "0d334ba77c225bc307ba537152f3f161" + + "0e4eafe595f6d9d90d11faa933a15ef1" + + "369546868a7f3a45a96768d40fd9d034" + + "12c091c6315cf4fde7cb68606937380d" + + "b2eaaa707b4c4185c32eddcdd306705e" + + "4dc1ffc872eeee475a64dfac86aba41c" + + "0618983f8741c5ef68d3a101e8a3b8ca" + + "c60c905c15fc910840b94c00a0b9d0"; + + CheckEd25519Vector( + ("f5e5767cf153319517630f226876b86c" + + "8160cc583bc013744c6bf255f5cc0ee5"), + ("278117fc144c72340f67d0f2316e8386" + + "ceffbf2b2428c9c51fef7c597f1d426e"), + m, + ("0aab4c900501b3e24d7cdf4663326a3a" + + "87df5e4843b2cbdb67cbf6e460fec350" + + "aa5371b1508f9f4528ecea23c436d94b" + + "5e8fcd4f681e30a6ac00a9704a188a03"), + "Ed25519 Vector #1023"); + } + + [Test] + public void TestEd25519VectorSHAabc() + { + CheckEd25519Vector( + ("833fe62409237b9d62ec77587520911e" + + "9a759cec1d19755b7da901b96dca3d42"), + ("ec172b93ad5e563bf4932c70e1245034" + + "c35467ef2efd4d64ebf819683467e2bf"), + ("ddaf35a193617abacc417349ae204131" + + "12e6fa4e89a97ea20a9eeee64b55d39a" + + "2192992a274fc1a836ba3c23a3feebbd" + + "454d4423643ce80e2a9ac94fa54ca49f"), + ("dc2a4459e7369633a52b1bf277839a00" + + "201009a3efbf3ecb69bea2186c26b589" + + "09351fc9ac90b3ecfdfbc7c66431e030" + + "3dca179c138ac17ad9bef1177331a704"), + "Ed25519 Vector SHA(abc)"); + } + + private static void CheckEd25519Vector(string sSK, string sPK, string sM, string sSig, string text) + { + byte[] sk = Hex.Decode(sSK); + + byte[] pk = Hex.Decode(sPK); + byte[] pkGen = new byte[Ed25519.PublicKeySize]; + Ed25519.GeneratePublicKey(sk, 0, pkGen, 0); + Assert.IsTrue(Arrays.AreEqual(pk, pkGen), text); + + byte[] m = Hex.Decode(sM); + byte[] sig = Hex.Decode(sSig); + byte[] sigGen = new byte[Ed25519.SignatureSize]; + Ed25519.Sign(sk, 0, m, 0, m.Length, sigGen, 0); + Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text); + + Ed25519.Sign(sk, 0, pk, 0, m, 0, m.Length, sigGen, 0); + Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text); + + bool shouldVerify = Ed25519.Verify(sig, 0, pk, 0, m, 0, m.Length); + Assert.IsTrue(shouldVerify, text); + + sig[Ed25519.SignatureSize - 1] ^= 0x80; + bool shouldNotVerify = Ed25519.Verify(sig, 0, pk, 0, m, 0, m.Length); + Assert.IsFalse(shouldNotVerify, text); + } + } +} diff --git a/crypto/test/src/math/ec/rfc8032/test/Ed448Test.cs b/crypto/test/src/math/ec/rfc8032/test/Ed448Test.cs new file mode 100644 index 000000000..98c487c09 --- /dev/null +++ b/crypto/test/src/math/ec/rfc8032/test/Ed448Test.cs @@ -0,0 +1,400 @@ +using System; + +using NUnit.Framework; + +using Org.BouncyCastle.Security; +using Org.BouncyCastle.Utilities; +using Org.BouncyCastle.Utilities.Encoders; + +namespace Org.BouncyCastle.Math.EC.Rfc8032.Tests +{ + [TestFixture] + public class Ed448Test + { + private static readonly SecureRandom Random = new SecureRandom(); + + [SetUp] + public void SetUp() + { + Ed448.Precompute(); + } + + [Test] + public void TestEd448Consistency() + { + byte[] sk = new byte[Ed448.SecretKeySize]; + byte[] pk = new byte[Ed448.PublicKeySize]; + byte[] ctx = new byte[Random.Next() & 7]; + byte[] m = new byte[255]; + byte[] sig1 = new byte[Ed448.SignatureSize]; + byte[] sig2 = new byte[Ed448.SignatureSize]; + + Random.NextBytes(ctx); + Random.NextBytes(m); + + for (int i = 0; i < 10; ++i) + { + Random.NextBytes(sk); + Ed448.GeneratePublicKey(sk, 0, pk, 0); + + int mLen = Random.Next() & 255; + + Ed448.Sign(sk, 0, ctx, m, 0, mLen, sig1, 0); + Ed448.Sign(sk, 0, pk, 0, ctx, m, 0, mLen, sig2, 0); + + Assert.IsTrue(Arrays.AreEqual(sig1, sig2), "Consistent signatures #" + i); + + bool shouldVerify = Ed448.Verify(sig1, 0, pk, 0, ctx, m, 0, mLen); + + Assert.IsTrue(shouldVerify, "Consistent sign/verify #" + i); + + sig1[Ed448.PublicKeySize - 1] ^= 0x80; + bool shouldNotVerify = Ed448.Verify(sig1, 0, pk, 0, ctx, m, 0, mLen); + + Assert.IsFalse(shouldNotVerify, "Consistent verification failure #" + i); + } + } + + [Test] + public void TestEd448Vector1() + { + CheckEd448Vector( + ( "6c82a562cb808d10d632be89c8513ebf" + + "6c929f34ddfa8c9f63c9960ef6e348a3" + + "528c8a3fcc2f044e39a3fc5b94492f8f" + + "032e7549a20098f95b"), + ( "5fd7449b59b461fd2ce787ec616ad46a" + + "1da1342485a70e1f8a0ea75d80e96778" + + "edf124769b46c7061bd6783df1e50f6c" + + "d1fa1abeafe8256180"), + "", + "", + ( "533a37f6bbe457251f023c0d88f976ae" + + "2dfb504a843e34d2074fd823d41a591f" + + "2b233f034f628281f2fd7a22ddd47d78" + + "28c59bd0a21bfd3980ff0d2028d4b18a" + + "9df63e006c5d1c2d345b925d8dc00b41" + + "04852db99ac5c7cdda8530a113a0f4db" + + "b61149f05a7363268c71d95808ff2e65" + + "2600"), + "Ed448 Vector #1"); + } + + [Test] + public void TestEd448Vector2() + { + CheckEd448Vector( + ( "c4eab05d357007c632f3dbb48489924d" + + "552b08fe0c353a0d4a1f00acda2c463a" + + "fbea67c5e8d2877c5e3bc397a659949e" + + "f8021e954e0a12274e"), + ( "43ba28f430cdff456ae531545f7ecd0a" + + "c834a55d9358c0372bfa0c6c6798c086" + + "6aea01eb00742802b8438ea4cb82169c" + + "235160627b4c3a9480"), + "03", + "", + ( "26b8f91727bd62897af15e41eb43c377" + + "efb9c610d48f2335cb0bd0087810f435" + + "2541b143c4b981b7e18f62de8ccdf633" + + "fc1bf037ab7cd779805e0dbcc0aae1cb" + + "cee1afb2e027df36bc04dcecbf154336" + + "c19f0af7e0a6472905e799f1953d2a0f" + + "f3348ab21aa4adafd1d234441cf807c0" + + "3a00"), + "Ed448 Vector #2"); + } + + [Test] + public void TestEd448Vector3() + { + CheckEd448Vector( + ( "c4eab05d357007c632f3dbb48489924d" + + "552b08fe0c353a0d4a1f00acda2c463a" + + "fbea67c5e8d2877c5e3bc397a659949e" + + "f8021e954e0a12274e"), + ( "43ba28f430cdff456ae531545f7ecd0a" + + "c834a55d9358c0372bfa0c6c6798c086" + + "6aea01eb00742802b8438ea4cb82169c" + + "235160627b4c3a9480"), + "03", + "666f6f", + ( "d4f8f6131770dd46f40867d6fd5d5055" + + "de43541f8c5e35abbcd001b32a89f7d2" + + "151f7647f11d8ca2ae279fb842d60721" + + "7fce6e042f6815ea000c85741de5c8da" + + "1144a6a1aba7f96de42505d7a7298524" + + "fda538fccbbb754f578c1cad10d54d0d" + + "5428407e85dcbc98a49155c13764e66c" + + "3c00"), + "Ed448 Vector #3"); + } + + [Test] + public void TestEd448Vector4() + { + CheckEd448Vector( + ( "cd23d24f714274e744343237b93290f5" + + "11f6425f98e64459ff203e8985083ffd" + + "f60500553abc0e05cd02184bdb89c4cc" + + "d67e187951267eb328"), + ( "dcea9e78f35a1bf3499a831b10b86c90" + + "aac01cd84b67a0109b55a36e9328b1e3" + + "65fce161d71ce7131a543ea4cb5f7e9f" + + "1d8b00696447001400"), + "0c3e544074ec63b0265e0c", + "", + ( "1f0a8888ce25e8d458a21130879b840a" + + "9089d999aaba039eaf3e3afa090a09d3" + + "89dba82c4ff2ae8ac5cdfb7c55e94d5d" + + "961a29fe0109941e00b8dbdeea6d3b05" + + "1068df7254c0cdc129cbe62db2dc957d" + + "bb47b51fd3f213fb8698f064774250a5" + + "028961c9bf8ffd973fe5d5c206492b14" + + "0e00"), + "Ed448 Vector #4"); + } + + [Test] + public void TestEd448Vector5() + { + CheckEd448Vector( + ( "258cdd4ada32ed9c9ff54e63756ae582" + + "fb8fab2ac721f2c8e676a72768513d93" + + "9f63dddb55609133f29adf86ec9929dc" + + "cb52c1c5fd2ff7e21b"), + ( "3ba16da0c6f2cc1f30187740756f5e79" + + "8d6bc5fc015d7c63cc9510ee3fd44adc" + + "24d8e968b6e46e6f94d19b945361726b" + + "d75e149ef09817f580"), + "64a65f3cdedcdd66811e2915", + "", + ( "7eeeab7c4e50fb799b418ee5e3197ff6" + + "bf15d43a14c34389b59dd1a7b1b85b4a" + + "e90438aca634bea45e3a2695f1270f07" + + "fdcdf7c62b8efeaf00b45c2c96ba457e" + + "b1a8bf075a3db28e5c24f6b923ed4ad7" + + "47c3c9e03c7079efb87cb110d3a99861" + + "e72003cbae6d6b8b827e4e6c143064ff" + + "3c00"), + "Ed448 Vector #5"); + } + + [Test] + public void TestEd448Vector6() + { + CheckEd448Vector( + ( "7ef4e84544236752fbb56b8f31a23a10" + + "e42814f5f55ca037cdcc11c64c9a3b29" + + "49c1bb60700314611732a6c2fea98eeb" + + "c0266a11a93970100e"), + ( "b3da079b0aa493a5772029f0467baebe" + + "e5a8112d9d3a22532361da294f7bb381" + + "5c5dc59e176b4d9f381ca0938e13c6c0" + + "7b174be65dfa578e80"), + "64a65f3cdedcdd66811e2915e7", + "", + ( "6a12066f55331b6c22acd5d5bfc5d712" + + "28fbda80ae8dec26bdd306743c5027cb" + + "4890810c162c027468675ecf645a8317" + + "6c0d7323a2ccde2d80efe5a1268e8aca" + + "1d6fbc194d3f77c44986eb4ab4177919" + + "ad8bec33eb47bbb5fc6e28196fd1caf5" + + "6b4e7e0ba5519234d047155ac727a105" + + "3100"), + "Ed448 Vector #6"); + } + + [Test] + public void TestEd448Vector64() + { + string m = + "bd0f6a3747cd561bdddf4640a332461a" + + "4a30a12a434cd0bf40d766d9c6d458e5" + + "512204a30c17d1f50b5079631f64eb31" + + "12182da3005835461113718d1a5ef944"; + + CheckEd448Vector( + ( "d65df341ad13e008567688baedda8e9d" + + "cdc17dc024974ea5b4227b6530e339bf" + + "f21f99e68ca6968f3cca6dfe0fb9f4fa" + + "b4fa135d5542ea3f01"), + ( "df9705f58edbab802c7f8363cfe5560a" + + "b1c6132c20a9f1dd163483a26f8ac53a" + + "39d6808bf4a1dfbd261b099bb03b3fb5" + + "0906cb28bd8a081f00"), + m, + "", + ( "554bc2480860b49eab8532d2a533b7d5" + + "78ef473eeb58c98bb2d0e1ce488a98b1" + + "8dfde9b9b90775e67f47d4a1c3482058" + + "efc9f40d2ca033a0801b63d45b3b722e" + + "f552bad3b4ccb667da350192b61c508c" + + "f7b6b5adadc2c8d9a446ef003fb05cba" + + "5f30e88e36ec2703b349ca229c267083" + + "3900"), + "Ed448 Vector #64"); + } + + [Test] + public void TestEd448Vector256() + { + string m = + "15777532b0bdd0d1389f636c5f6b9ba7" + + "34c90af572877e2d272dd078aa1e567c" + + "fa80e12928bb542330e8409f31745041" + + "07ecd5efac61ae7504dabe2a602ede89" + + "e5cca6257a7c77e27a702b3ae39fc769" + + "fc54f2395ae6a1178cab4738e543072f" + + "c1c177fe71e92e25bf03e4ecb72f47b6" + + "4d0465aaea4c7fad372536c8ba516a60" + + "39c3c2a39f0e4d832be432dfa9a706a6" + + "e5c7e19f397964ca4258002f7c0541b5" + + "90316dbc5622b6b2a6fe7a4abffd9610" + + "5eca76ea7b98816af0748c10df048ce0" + + "12d901015a51f189f3888145c03650aa" + + "23ce894c3bd889e030d565071c59f409" + + "a9981b51878fd6fc110624dcbcde0bf7" + + "a69ccce38fabdf86f3bef6044819de11"; + + CheckEd448Vector( + ( "2ec5fe3c17045abdb136a5e6a913e32a" + + "b75ae68b53d2fc149b77e504132d3756" + + "9b7e766ba74a19bd6162343a21c8590a" + + "a9cebca9014c636df5"), + ( "79756f014dcfe2079f5dd9e718be4171" + + "e2ef2486a08f25186f6bff43a9936b9b" + + "fe12402b08ae65798a3d81e22e9ec80e" + + "7690862ef3d4ed3a00"), + m, + "", + ( "c650ddbb0601c19ca11439e1640dd931" + + "f43c518ea5bea70d3dcde5f4191fe53f" + + "00cf966546b72bcc7d58be2b9badef28" + + "743954e3a44a23f880e8d4f1cfce2d7a" + + "61452d26da05896f0a50da66a239a8a1" + + "88b6d825b3305ad77b73fbac0836ecc6" + + "0987fd08527c1a8e80d5823e65cafe2a" + + "3d00"), + "Ed448 Vector #256"); + } + + [Test] + public void TestEd448Vector1023() + { + string m = + "6ddf802e1aae4986935f7f981ba3f035" + + "1d6273c0a0c22c9c0e8339168e675412" + + "a3debfaf435ed651558007db4384b650" + + "fcc07e3b586a27a4f7a00ac8a6fec2cd" + + "86ae4bf1570c41e6a40c931db27b2faa" + + "15a8cedd52cff7362c4e6e23daec0fbc" + + "3a79b6806e316efcc7b68119bf46bc76" + + "a26067a53f296dafdbdc11c77f7777e9" + + "72660cf4b6a9b369a6665f02e0cc9b6e" + + "dfad136b4fabe723d2813db3136cfde9" + + "b6d044322fee2947952e031b73ab5c60" + + "3349b307bdc27bc6cb8b8bbd7bd32321" + + "9b8033a581b59eadebb09b3c4f3d2277" + + "d4f0343624acc817804728b25ab79717" + + "2b4c5c21a22f9c7839d64300232eb66e" + + "53f31c723fa37fe387c7d3e50bdf9813" + + "a30e5bb12cf4cd930c40cfb4e1fc6225" + + "92a49588794494d56d24ea4b40c89fc0" + + "596cc9ebb961c8cb10adde976a5d602b" + + "1c3f85b9b9a001ed3c6a4d3b1437f520" + + "96cd1956d042a597d561a596ecd3d173" + + "5a8d570ea0ec27225a2c4aaff26306d1" + + "526c1af3ca6d9cf5a2c98f47e1c46db9" + + "a33234cfd4d81f2c98538a09ebe76998" + + "d0d8fd25997c7d255c6d66ece6fa56f1" + + "1144950f027795e653008f4bd7ca2dee" + + "85d8e90f3dc315130ce2a00375a318c7" + + "c3d97be2c8ce5b6db41a6254ff264fa6" + + "155baee3b0773c0f497c573f19bb4f42" + + "40281f0b1f4f7be857a4e59d416c06b4" + + "c50fa09e1810ddc6b1467baeac5a3668" + + "d11b6ecaa901440016f389f80acc4db9" + + "77025e7f5924388c7e340a732e554440" + + "e76570f8dd71b7d640b3450d1fd5f041" + + "0a18f9a3494f707c717b79b4bf75c984" + + "00b096b21653b5d217cf3565c9597456" + + "f70703497a078763829bc01bb1cbc8fa" + + "04eadc9a6e3f6699587a9e75c94e5bab" + + "0036e0b2e711392cff0047d0d6b05bd2" + + "a588bc109718954259f1d86678a579a3" + + "120f19cfb2963f177aeb70f2d4844826" + + "262e51b80271272068ef5b3856fa8535" + + "aa2a88b2d41f2a0e2fda7624c2850272" + + "ac4a2f561f8f2f7a318bfd5caf969614" + + "9e4ac824ad3460538fdc25421beec2cc" + + "6818162d06bbed0c40a387192349db67" + + "a118bada6cd5ab0140ee273204f628aa" + + "d1c135f770279a651e24d8c14d75a605" + + "9d76b96a6fd857def5e0b354b27ab937" + + "a5815d16b5fae407ff18222c6d1ed263" + + "be68c95f32d908bd895cd76207ae7264" + + "87567f9a67dad79abec316f683b17f2d" + + "02bf07e0ac8b5bc6162cf94697b3c27c" + + "d1fea49b27f23ba2901871962506520c" + + "392da8b6ad0d99f7013fbc06c2c17a56" + + "9500c8a7696481c1cd33e9b14e40b82e" + + "79a5f5db82571ba97bae3ad3e0479515" + + "bb0e2b0f3bfcd1fd33034efc6245eddd" + + "7ee2086ddae2600d8ca73e214e8c2b0b" + + "db2b047c6a464a562ed77b73d2d841c4" + + "b34973551257713b753632efba348169" + + "abc90a68f42611a40126d7cb21b58695" + + "568186f7e569d2ff0f9e745d0487dd2e" + + "b997cafc5abf9dd102e62ff66cba87"; + + CheckEd448Vector( + ( "872d093780f5d3730df7c212664b37b8" + + "a0f24f56810daa8382cd4fa3f77634ec" + + "44dc54f1c2ed9bea86fafb7632d8be19" + + "9ea165f5ad55dd9ce8"), + ( "a81b2e8a70a5ac94ffdbcc9badfc3feb" + + "0801f258578bb114ad44ece1ec0e799d" + + "a08effb81c5d685c0c56f64eecaef8cd" + + "f11cc38737838cf400"), + m, + "", + ( "e301345a41a39a4d72fff8df69c98075" + + "a0cc082b802fc9b2b6bc503f926b65bd" + + "df7f4c8f1cb49f6396afc8a70abe6d8a" + + "ef0db478d4c6b2970076c6a0484fe76d" + + "76b3a97625d79f1ce240e7c576750d29" + + "5528286f719b413de9ada3e8eb78ed57" + + "3603ce30d8bb761785dc30dbc320869e" + + "1a00"), + "Ed448 Vector #1023"); + } + + private static void CheckEd448Vector(string sSK, string sPK, string sM, string sCTX, string sSig, string text) + { + byte[] sk = Hex.Decode(sSK); + + byte[] pk = Hex.Decode(sPK); + byte[] pkGen = new byte[Ed448.PublicKeySize]; + Ed448.GeneratePublicKey(sk, 0, pkGen, 0); + Assert.IsTrue(Arrays.AreEqual(pk, pkGen), text); + + byte[] m = Hex.Decode(sM); + byte[] ctx = Hex.Decode(sCTX); + byte[] sig = Hex.Decode(sSig); + byte[] sigGen = new byte[Ed448.SignatureSize]; + Ed448.Sign(sk, 0, ctx, m, 0, m.Length, sigGen, 0); + Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text); + + Ed448.Sign(sk, 0, pk, 0, ctx, m, 0, m.Length, sigGen, 0); + Assert.IsTrue(Arrays.AreEqual(sig, sigGen), text); + + bool shouldVerify = Ed448.Verify(sig, 0, pk, 0, ctx, m, 0, m.Length); + Assert.IsTrue(shouldVerify, text); + + sig[Ed448.SignatureSize - 1] ^= 0x80; + bool shouldNotVerify = Ed448.Verify(sig, 0, pk, 0, ctx, m, 0, m.Length); + Assert.IsFalse(shouldNotVerify, text); + } + } +} diff --git a/crypto/test/src/math/ec/test/ECPointTest.cs b/crypto/test/src/math/ec/test/ECPointTest.cs index 089fb88b3..a5ca083e2 100644 --- a/crypto/test/src/math/ec/test/ECPointTest.cs +++ b/crypto/test/src/math/ec/test/ECPointTest.cs @@ -442,6 +442,22 @@ namespace Org.BouncyCastle.Math.EC.Tests } } + private void ImplValidityTest(ECCurve c, ECPoint g) + { + Assert.IsTrue(g.IsValid()); + + BigInteger h = c.Cofactor; + if (h != null && h.CompareTo(BigInteger.One) > 0) + { + if (ECAlgorithms.IsF2mCurve(c)) + { + ECPoint order2 = c.CreatePoint(BigInteger.Zero, c.B.Sqrt().ToBigInteger()); + ECPoint bad = g.Add(order2); + Assert.IsFalse(bad.IsValid()); + } + } + } + private void ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(X9ECParameters x9ECParameters) { BigInteger n = x9ECParameters.N; @@ -470,6 +486,8 @@ namespace Org.BouncyCastle.Math.EC.Tests ImplAddSubtractMultiplyTwiceEncodingTest(c, q, n); ImplSqrtTest(c); + + ImplValidityTest(c, g); } } } diff --git a/crypto/test/src/security/test/TestEncodings.cs b/crypto/test/src/security/test/TestEncodings.cs index 557d2dc51..a70d5b5b7 100644 --- a/crypto/test/src/security/test/TestEncodings.cs +++ b/crypto/test/src/security/test/TestEncodings.cs @@ -32,24 +32,19 @@ namespace Org.BouncyCastle.Security.Tests BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); BigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo")); - FpCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters ecDomain = - new ECDomainParameters( - curve, - new FpPoint(curve, - curve.FromBigInteger(ECParraGX), - curve.FromBigInteger(ECParraGY)), - ECParraN); - - ECPublicKeyParameters ecPub = new ECPublicKeyParameters( - new FpPoint( - curve, - curve.FromBigInteger(ECPubQX), - curve.FromBigInteger(ECPubQY)), + FpCurve curve = new FpCurve( + new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q + new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a + new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16), // b + ECParraN, ECParraH); + + ECDomainParameters ecDomain = new ECDomainParameters( + curve, + curve.ValidatePoint(ECParraGX, ECParraGY), + ECParraN, ECParraH); + + ECPublicKeyParameters ecPub = new ECPublicKeyParameters( + curve.ValidatePoint(ECPubQX, ECPubQY), ecDomain); ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain); diff --git a/crypto/test/src/security/test/TestSignerUtil.cs b/crypto/test/src/security/test/TestSignerUtil.cs index d815d53a5..144ab67b1 100644 --- a/crypto/test/src/security/test/TestSignerUtil.cs +++ b/crypto/test/src/security/test/TestSignerUtil.cs @@ -56,18 +56,16 @@ namespace Org.BouncyCastle.Security.Tests FpCurve curve = new FpCurve( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b + new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16), // b + ECParraN, ECParraH); - ECDomainParameters ecDomain = new ECDomainParameters(curve, - new FpPoint(curve, - curve.FromBigInteger(ECParraGX), - curve.FromBigInteger(ECParraGY)), - ECParraN); + ECDomainParameters ecDomain = new ECDomainParameters( + curve, + curve.ValidatePoint(ECParraGX, ECParraGY), + ECParraN, ECParraH); ECPublicKeyParameters ecPub = new ECPublicKeyParameters( - new FpPoint(curve, - curve.FromBigInteger(ECPubQX), - curve.FromBigInteger(ECPubQY)), + curve.ValidatePoint(ECPubQX, ECPubQY), ecDomain); ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain); diff --git a/crypto/test/src/test/CertTest.cs b/crypto/test/src/test/CertTest.cs index 9a4965297..e3ce9df79 100644 --- a/crypto/test/src/test/CertTest.cs +++ b/crypto/test/src/test/CertTest.cs @@ -1391,15 +1391,9 @@ namespace Org.BouncyCastle.Tests */ internal void checkCreation3() { - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters spec = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters spec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( "ECDSA", @@ -1533,16 +1527,9 @@ namespace Org.BouncyCastle.Tests string algorithm, DerObjectIdentifier algOid) { - FpCurve curve = new FpCurve( - new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) - new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a - new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b - - ECDomainParameters spec = new ECDomainParameters( - curve, -// curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G - curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G - new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("secp521r1"); + ECCurve curve = x9.Curve; + ECDomainParameters spec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( "ECDSA", diff --git a/crypto/test/src/test/DHTest.cs b/crypto/test/src/test/DHTest.cs index da31673de..f4eee348b 100644 --- a/crypto/test/src/test/DHTest.cs +++ b/crypto/test/src/test/DHTest.cs @@ -2,6 +2,7 @@ using System; using NUnit.Framework; +using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; @@ -375,37 +376,22 @@ namespace Org.BouncyCastle.Tests [Test] public void TestECDH() { - doTestECDH("ECDH"); + DoTestECDH("ECDH"); } [Test] public void TestECDHC() { - doTestECDH("ECDHC"); + DoTestECDH("ECDHC"); } - private void doTestECDH( - string algorithm) + private void DoTestECDH(string algorithm) { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm); -// EllipticCurve curve = new EllipticCurve( -// new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q -// new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a -// new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters ecSpec = new ECDomainParameters( - curve, -// ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n - BigInteger.One); //1); // h - -// g.initialize(ecSpec, new SecureRandom()); + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H); + g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // @@ -429,11 +415,6 @@ namespace Org.BouncyCastle.Tests // // agreement // -// aKeyAgreeBasic.doPhase(bKeyPair.Public, true); -// bKeyAgreeBasic.doPhase(aKeyPair.Public, true); -// -// BigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret()); -// BigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret()); BigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public); BigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public); diff --git a/crypto/test/src/test/DSATest.cs b/crypto/test/src/test/DSATest.cs index d7382d256..fb483dca7 100644 --- a/crypto/test/src/test/DSATest.cs +++ b/crypto/test/src/test/DSATest.cs @@ -252,15 +252,9 @@ namespace Org.BouncyCastle.Tests SecureRandom k = FixedSecureRandom.From(kData); - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters spec = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters spec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters priKey = new ECPrivateKeyParameters( "ECDSA", @@ -330,17 +324,9 @@ namespace Org.BouncyCastle.Tests SecureRandom k = FixedSecureRandom.From(kData); - ECCurve curve = new F2mCurve( - 239, // m - 36, // k - new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a - new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b - - ECDomainParameters parameters = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G - new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n - BigInteger.ValueOf(4)); // h + X9ECParameters x9 = ECNamedCurveTable.GetByName("c2tnb239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters parameters = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters sKey = new ECPrivateKeyParameters( "ECDSA", @@ -435,17 +421,9 @@ namespace Org.BouncyCastle.Tests SecureRandom k = FixedSecureRandom.From(kData); - ECCurve curve = new F2mCurve( - 239, // m - 36, // k - new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a - new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b - - ECDomainParameters parameters = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G - new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n - BigInteger.ValueOf(4)); // h + X9ECParameters x9 = ECNamedCurveTable.GetByName("c2tnb239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters parameters = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters sKey = new ECPrivateKeyParameters( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d @@ -554,15 +532,9 @@ namespace Org.BouncyCastle.Tests // s = SignerUtilities.GetSigner("ECDSA"); - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters ecSpec = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); @@ -594,17 +566,9 @@ namespace Org.BouncyCastle.Tests // s = SignerUtilities.GetSigner("ECDSA"); - curve = new F2mCurve( - 239, // m - 36, // k - new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a - new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b - - ecSpec = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G - new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n - BigInteger.ValueOf(4)); // h + x9 = ECNamedCurveTable.GetByName("c2tnb239v1"); + curve = x9.Curve; + ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); g.Init(new ECKeyGenerationParameters(ecSpec, rand)); diff --git a/crypto/test/src/test/GOST3410Test.cs b/crypto/test/src/test/GOST3410Test.cs index 931332cfb..17a079470 100644 --- a/crypto/test/src/test/GOST3410Test.cs +++ b/crypto/test/src/test/GOST3410Test.cs @@ -29,19 +29,21 @@ namespace Org.BouncyCastle.Tests SecureRandom k = FixedSecureRandom.From(kData); - BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p + BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); + BigInteger mod_q = new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619"); ECCurve curve = new FpCurve( - mod_p, // p + mod_p, new BigInteger("7"), // a - new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b + new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414"), // b + mod_q, BigInteger.One); ECDomainParameters spec = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("2"), new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), - new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q + mod_q, BigInteger.One); ECPrivateKeyParameters sKey = new ECPrivateKeyParameters( "ECGOST3410", @@ -193,19 +195,21 @@ namespace Org.BouncyCastle.Tests s = SignerUtilities.GetSigner("ECGOST3410"); g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); - BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p + BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); + BigInteger mod_q = new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619"); ECCurve curve = new FpCurve( - mod_p, // p + mod_p, new BigInteger("7"), // a - new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b + new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414"), // b + mod_q, BigInteger.One); ECDomainParameters ecSpec = new ECDomainParameters( curve, curve.CreatePoint( new BigInteger("2"), new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280")), - new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q + mod_q, BigInteger.One); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); diff --git a/crypto/test/src/test/IESTest.cs b/crypto/test/src/test/IESTest.cs index 812b05f97..fee2d7817 100644 --- a/crypto/test/src/test/IESTest.cs +++ b/crypto/test/src/test/IESTest.cs @@ -32,15 +32,8 @@ namespace Org.BouncyCastle.Tests { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECIES"); - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters ecSpec = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H); g.Init( new ECKeyGenerationParameters( diff --git a/crypto/test/src/test/MqvTest.cs b/crypto/test/src/test/MqvTest.cs index ec5c610ca..401fb3922 100644 --- a/crypto/test/src/test/MqvTest.cs +++ b/crypto/test/src/test/MqvTest.cs @@ -2,6 +2,7 @@ using System; using NUnit.Framework; +using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; @@ -31,24 +32,10 @@ namespace Org.BouncyCastle.Tests { IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECMQV"); -// EllipticCurve curve = new EllipticCurve( -// new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q -// new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a -// new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECDomainParameters ecSpec = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H); - ECDomainParameters ecSpec = new ECDomainParameters( - curve, -// ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"), // n - BigInteger.One); //1); // h - -// g.initialize(ecSpec, new SecureRandom()); - g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); + g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // U side diff --git a/crypto/test/src/test/PKCS10CertRequestTest.cs b/crypto/test/src/test/PKCS10CertRequestTest.cs index 7c96baea1..df10cad3f 100644 --- a/crypto/test/src/test/PKCS10CertRequestTest.cs +++ b/crypto/test/src/test/PKCS10CertRequestTest.cs @@ -126,16 +126,9 @@ namespace Org.BouncyCastle.Tests string algorithm, DerObjectIdentifier algOid) { - FpCurve curve = new FpCurve( - new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) - new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), // a - new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); // b - - ECDomainParameters spec = new ECDomainParameters( - curve, -// curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G - curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G - new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("secp521r1"); + ECCurve curve = x9.Curve; + ECDomainParameters spec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); ECPrivateKeyParameters privKey = new ECPrivateKeyParameters( new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d @@ -413,15 +406,9 @@ namespace Org.BouncyCastle.Tests // elliptic curve openSSL IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); - ECCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - - ECDomainParameters ecSpec = new ECDomainParameters( - curve, - curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G - new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); diff --git a/crypto/test/src/x509/test/TestCertificateGen.cs b/crypto/test/src/x509/test/TestCertificateGen.cs index 019c2a460..670bf75c2 100644 --- a/crypto/test/src/x509/test/TestCertificateGen.cs +++ b/crypto/test/src/x509/test/TestCertificateGen.cs @@ -5,6 +5,7 @@ using System.Text; using NUnit.Framework; using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; @@ -222,20 +223,14 @@ namespace Org.BouncyCastle.X509.Tests BigInteger ECPubQX = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l")); BigInteger ECPubQY = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx")); BigInteger ECPrivD = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo")); - FpCurve curve = new FpCurve( - new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q - new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a - new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b - ECDomainParameters ecDomain = - new ECDomainParameters(curve, new FpPoint(curve, curve.FromBigInteger(ECParraGX), curve.FromBigInteger(ECParraGY)), ECParraN); - ECPublicKeyParameters ecPub = new ECPublicKeyParameters( - "ECDSA", - new FpPoint(curve, - curve.FromBigInteger(ECPubQX), - curve.FromBigInteger(ECPubQY)), - ecDomain); - ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain); + X9ECParameters x9 = ECNamedCurveTable.GetByName("prime239v1"); + ECCurve curve = x9.Curve; + ECDomainParameters ecDomain = new ECDomainParameters(curve, curve.ValidatePoint(ECParraGX, ECParraGY), ECParraN, ECParraH); + + ECPublicKeyParameters ecPub = new ECPublicKeyParameters("ECDSA", + curve.ValidatePoint(ECPubQX, ECPubQY), ecDomain); + ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters("ECDSA", ECPrivD, ecDomain); IDictionary attrs = new Hashtable(); attrs[X509Name.C] = "AU"; |