Beispiel #1
0
        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");
            }
        }
Beispiel #2
0
        public static ECDomainParameters GetParametersForNamedCurve(int namedCurve)
        {
            string curveName = GetNameOfNamedCurve(namedCurve);

            if (curveName == null)
            {
                return(null);
            }

            // Parameters are lazily created the first time a particular curve is accessed

            X9ECParameters ecP = CustomNamedCurves.GetByName(curveName);

            if (ecP == null)
            {
                ecP = ECNamedCurveTable.GetByName(curveName);
                if (ecP == null)
                {
                    return(null);
                }
            }

            // It's a bit inefficient to do this conversion every time
            return(new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()));
        }
        public void TestSumOfTwoMultiplies()
        {
            X9ECParameters x9 = CustomNamedCurves.GetByName("secp256r1");

            Assert.NotNull(x9);
            DoTestSumOfTwoMultiplies(x9);
        }
Beispiel #4
0
        public async Task GetActiveSigningKeyPair_GivenRotationAndMasterKeyCert_ReturnsAKeyPairUsableForTokenSigning()
        {
            //Arrange
            var automocker = new AutoMocker();

            var masterKey = new byte[256];

            object cachedResult = null;

            automocker
            .SetupOptions(new AnonymousTokensConfig
            {
                KeyRotationEnabled  = true,
                CurveName           = "P-256",
                MasterKeyCertId     = "master-key-cert",
                KeyRotationInterval = TimeSpan.FromDays(3),
                KeyRotationRollover = TimeSpan.FromDays(4)
            });

            automocker
            .Setup <IMemoryCache, bool>(x => x.TryGetValue(It.IsAny <string>(), out cachedResult))
            .Returns(false);

            automocker
            .Setup <IMemoryCache, ICacheEntry>(x => x.CreateEntry(It.IsAny <string>()))
            .Returns(Mock.Of <ICacheEntry>());

            automocker
            .Setup <IAnonymousTokenMasterKeyLoader, Task <byte[]> >(x => x.LoadMasterKeyBytes())
            .ReturnsAsync(masterKey);

            var target = automocker.CreateInstance <AnonymousTokenKeyStore>();

            //Act
            var result = await target.GetActiveSigningKeyPair();

            //Assert
            var ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1);
            var initiator    = new Initiator();
            var init         = initiator.Initiate(ecParameters.Curve);
            var t            = init.t;
            var r            = init.r;
            var P            = init.P;

            var tokenGenerator = new TokenGenerator();

            var(Q, c, z) = tokenGenerator.GenerateToken(result.PrivateKey, result.PublicKey, ecParameters, P);

            var keyDto = result.AsValidationKey().AsKeyDto();

            var clientSideEcParameters   = CustomNamedCurves.GetByName(keyDto.Crv); // Matches keyDto.Crv == "P-256"
            var clientSidePublicKeyPoint = clientSideEcParameters.Curve.CreatePoint(new BigInteger(Convert.FromBase64String(keyDto.X)), new BigInteger(Convert.FromBase64String(keyDto.Y)));

            var W = initiator.RandomiseToken(clientSideEcParameters, clientSidePublicKeyPoint, P, Q, c, z, r);

            var tokenVerifier = new TokenVerifier(new InMemorySeedStore());
            var isVerified    = await tokenVerifier.VerifyTokenAsync(result.PrivateKey, ecParameters.Curve, t, W);

            isVerified.Should().BeTrue();
        }
Beispiel #5
0
    private static AsymmetricKeyParameter LoadPublicKey(byte[] data)
    {
        X9ECParameters        ecP    = CustomNamedCurves.GetByName("curve25519");
        ECDomainParameters    ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
        ECPublicKeyParameters pubKey = new ECPublicKeyParameters(ecSpec.Curve.DecodePoint(data), ecSpec);

        return(pubKey);
    }
Beispiel #6
0
    public static AsymmetricKeyParameter LoadPrivateKey(byte[] data)
    {
        X9ECParameters         ecP    = CustomNamedCurves.GetByName("curve25519");
        ECDomainParameters     ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
        ECPrivateKeyParameters prvkey = new ECPrivateKeyParameters(new Org.BouncyCastle.Math.BigInteger(data), ecSpec);

        return(prvkey);
    }
        static KeyAgreement()
        {
            var curve = CustomNamedCurves.GetByName("secp256r1");

            domainParms = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            var m = domainParms.Curve.GetType().GetMethod("DecompressPoint", BindingFlags.NonPublic | BindingFlags.Instance);

            _decompress = (i, b) => (ECPoint)m.Invoke(domainParms.Curve, new object[] { i, b });
        }
Beispiel #8
0
        private static ECPoint DecodePublicKey(AnonymousTokenKey key)
        {
            var curve = CustomNamedCurves.GetByName(key.Crv);

            return(curve.Curve.CreatePoint(
                       new BigInteger(Convert.FromBase64String(key.X)),
                       new BigInteger(Convert.FromBase64String(key.Y))
                       ));
        }
        public static AsymmetricCipherKeyPair GenerateKeyPair(string curveName, string algorithm)
        {
            var ecP       = CustomNamedCurves.GetByName(curveName);
            var ecSpec    = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            var generator = (ECKeyPairGenerator)GeneratorUtilities.GetKeyPairGenerator(algorithm);

            generator.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
            return(generator.GenerateKeyPair());
        }
Beispiel #10
0
        private static ECPublicKeyParameters DecodePublicKey(AnonymousTokenKey key)
        {
            var curve = CustomNamedCurves.GetByName(key.Crv);
            var clientSidePublicKeyPoint = curve.Curve.CreatePoint(
                new BigInteger(Convert.FromBase64String(key.X)),
                new BigInteger(Convert.FromBase64String(key.Y))
                );

            return(new ECPublicKeyParameters("ECDSA", clientSidePublicKeyPoint, new ECDomainParameters(curve)));
        }
Beispiel #11
0
        private async Task <AnonymousTokenSigningKeypair> CreateKeyPairForInterval(long keyIntervalNumber)
        {
            var masterKeyBytes = await _masterKeyLoader.LoadMasterKeyBytes();

            var ecParameters     = CustomNamedCurves.GetByName(_config.CurveName);
            var keyPairGenerator = new RollingKeyPairGenerator(masterKeyBytes, ecParameters);

            var(privateKey, publicKey) = keyPairGenerator.GenerateKeyPairForInterval(keyIntervalNumber);
            return(new AnonymousTokenSigningKeypair(keyIntervalNumber.ToString(), _config.CurveName, privateKey, publicKey));
        }
Beispiel #12
0
        private static ECPoint GetPublicPointFromPrivate(BigInteger privateKeyPoint)
        {
            var CURVE_PARAMS = CustomNamedCurves.GetByName("secp256k1");
            var CURVE        = new ECDomainParameters(CURVE_PARAMS.Curve, CURVE_PARAMS.G, CURVE_PARAMS.N, CURVE_PARAMS.H);

            if (privateKeyPoint.BitLength > CURVE.N.BitLength)
            {
                privateKeyPoint = privateKeyPoint.Mod(CURVE.N);
            }
            return(new FixedPointCombMultiplier().Multiply(CURVE.G, privateKeyPoint));
        }
        public static IEnumerable <byte> GetDeriveKey(byte[] key1, AsymmetricCipherKeyPair senderKeyPair,
                                                      string curveName, string algorithm)
        {
            var ecP       = CustomNamedCurves.GetByName(curveName);
            var ecSpec    = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            var publicKey = new ECPublicKeyParameters(ecSpec.Curve.DecodePoint(key1), ecSpec);
            var agreement = AgreementUtilities.GetBasicAgreement(algorithm);

            agreement.Init(senderKeyPair.Private);
            var result = agreement.CalculateAgreement(publicKey);

            return(result.ToByteArrayUnsigned());
        }
Beispiel #14
0
        public static Bytes CreatePrivateKey()
        {
            var keyPairGenerator   = GeneratorUtilities.GetKeyPairGenerator("EC");
            var curveParams        = CustomNamedCurves.GetByName("secp256k1");
            var curve              = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H);
            var ecGenParameterSpec = new ECKeyGenerationParameters(curve, _secureRandom);

            keyPairGenerator.Init(ecGenParameterSpec);

            var keyPair = keyPairGenerator.GenerateKeyPair();

            return(new Bytes(((ECPrivateKeyParameters)keyPair.Private).D));
        }
Beispiel #15
0
        /// <summary>
        /// Initializes a new instance of <see cref="EllipticCurveAlgorithm"/> class.
        /// </summary>
        /// <param name="oid">Object Identifier of the curve</param>
        /// <param name="curveName">Curve name</param>
        protected EllipticCurveAlgorithm(string oid, string curveName)
        {
            if (curveName == null)
            {
                throw new ArgumentNullException("curveName");
            }
            if (oid == null)
            {
                throw new ArgumentNullException("oid");
            }

            CurveName = curveName;

            X9ECParameters x9 = CustomNamedCurves.GetByName(oid);

            if (x9 != null)
            {
                _info = new ECKeyParametersExt(x9);
            }
            else
            {
                DerObjectIdentifier oidDer;
                try
                {
                    oidDer = new DerObjectIdentifier(oid);
                }
                catch (FormatException)
                {
                    throw new InvalidOperationException("Unknown curve: '" + oid + "'.");
                }

                _info = new ECKeyParametersExt(oidDer);
            }

            BitLength = String.Equals(oid, "curve25519", StringComparison.OrdinalIgnoreCase)
                                ? 256
                                : _info.Parameters.N.BitLength;

            if (BitLength <= 256)
            {
                SignatureAlgorithm = "SHA-256withECDSA";
            }
            else if (BitLength <= 384)
            {
                SignatureAlgorithm = "SHA-384withECDSA";
            }
            else
            {
                SignatureAlgorithm = "SHA-512withECDSA";
            }
        }
Beispiel #16
0
        public void TestAddSubtractMultiplyTwiceEncoding()
        {
            foreach (string name in ECNamedCurveTable.Names)
            {
                X9ECParameters x9ECParameters = ECNamedCurveTable.GetByName(name);
                ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9ECParameters);

                x9ECParameters = CustomNamedCurves.GetByName(name);
                if (x9ECParameters != null)
                {
                    ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9ECParameters);
                }
            }
        }
Beispiel #17
0
        private static X9ECParameters GetCurveParameters(string name)
        {
            X9ECParameters byName = CustomNamedCurves.GetByName(name);

            if (byName == null)
            {
                byName = ECNamedCurveTable.GetByName(name);
            }
            if (byName == null)
            {
                throw new Exception("unknown curve name: " + name);
            }
            return(byName);
        }
        private void RandMult(string curveName)
        {
            X9ECParameters spec = ECNamedCurveTable.GetByName(curveName);

            if (spec != null)
            {
                RandMult(curveName, spec);
            }

            spec = CustomNamedCurves.GetByName(curveName);
            if (spec != null)
            {
                RandMult(curveName + " (custom)", spec);
            }
        }
        /**
         * Retrieve an EC based domain parameter by parameter ID. A custom curve will be returned if one is available.
         *
         * @param paramID identifier for the domain parameters.
         * @return the matching domain parameters if found, null otherwise.
         */
        public static NamedECDomainParameters LookupDomainParameters(IECDomainParametersID paramID)
        {
            X9ECParameters rv = CustomNamedCurves.GetByName(paramID.CurveName);

            if (rv == null)
            {
                rv = ECNamedCurveTable.GetByName(paramID.CurveName);
            }

            if (rv != null)
            {
                return(new NamedECDomainParameters(ECNamedCurveTable.GetOid(paramID.CurveName), rv.Curve, rv.G, rv.N, rv.H, rv.GetSeed()));
            }

            return(null);
        }
Beispiel #20
0
        public static void NewKey()
        {
            if (false)
            {
                X9ECParameters p = NistNamedCurves.GetByName("P-256");

                ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);

                ECKeyPairGenerator        pGen     = new ECKeyPairGenerator();
                ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, new Org.BouncyCastle.Security.SecureRandom());
                pGen.Init(genParam);

                AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair();

                CBORObject epk = CBORObject.NewMap();
                epk.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_EC);
                epk.Add(CoseKeyParameterKeys.EC_Curve, "P-384");
                ECPublicKeyParameters priv = (ECPublicKeyParameters)p1.Public;
                epk.Add(CoseKeyParameterKeys.EC_X, priv.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned());
                epk.Add(CoseKeyParameterKeys.EC_Y, priv.Q.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned());
                epk.Add(CoseKeyParameterKeys.EC_D, ((ECPrivateKeyParameters)p1.Private).D.ToByteArrayUnsigned());

                string xxx = epk.ToJSONString();
            }
            else
            {
                X9ECParameters p = CustomNamedCurves.GetByName("CURVE25519");

                ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);

                ECKeyPairGenerator        pGen     = new ECKeyPairGenerator();
                ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(parameters, new Org.BouncyCastle.Security.SecureRandom());
                pGen.Init(genParam);

                AsymmetricCipherKeyPair p1 = pGen.GenerateKeyPair();

                CBORObject epk = CBORObject.NewMap();
                epk.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_OKP);
                epk.Add(CoseKeyParameterKeys.OKP_Curve, GeneralValues.X25519);
                ECPublicKeyParameters priv = (ECPublicKeyParameters)p1.Public;
                epk.Add(CoseKeyParameterKeys.EC_X, priv.Q.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned());
                epk.Add(CoseKeyParameterKeys.EC_D, ((ECPrivateKeyParameters)p1.Private).D.ToByteArrayUnsigned());

                string xxx = epk.ToJSONString();
            }
        }
Beispiel #21
0
        public void TestAddSubtractMultiplyTwiceEncoding()
        {
            ArrayList names = new ArrayList();

            CollectionUtilities.AddRange(names, ECNamedCurveTable.Names);
            CollectionUtilities.AddRange(names, CustomNamedCurves.Names);

            ISet uniqNames = new HashSet(names);

            foreach (string name in uniqNames)
            {
                X9ECParameters x9A = ECNamedCurveTable.GetByName(name);
                X9ECParameters x9B = CustomNamedCurves.GetByName(name);

                if (x9A != null && x9B != null)
                {
                    Assert.AreEqual(x9A.Curve.Field, x9B.Curve.Field);
                    Assert.AreEqual(x9A.Curve.A.ToBigInteger(), x9B.Curve.A.ToBigInteger());
                    Assert.AreEqual(x9A.Curve.B.ToBigInteger(), x9B.Curve.B.ToBigInteger());
                    AssertOptionalValuesAgree(x9A.Curve.Cofactor, x9B.Curve.Cofactor);
                    AssertOptionalValuesAgree(x9A.Curve.Order, x9B.Curve.Order);

                    AssertPointsEqual("Custom curve base-point inconsistency", x9A.G, x9B.G);

                    Assert.AreEqual(x9A.H, x9B.H);
                    Assert.AreEqual(x9A.N, x9B.N);
                    AssertOptionalValuesAgree(x9A.GetSeed(), x9B.GetSeed());

                    BigInteger k  = new BigInteger(x9A.N.BitLength, secRand);
                    ECPoint    pA = x9A.G.Multiply(k);
                    ECPoint    pB = x9B.G.Multiply(k);
                    AssertPointsEqual("Custom curve multiplication inconsistency", pA, pB);
                }

                if (x9A != null)
                {
                    ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9A);
                }

                if (x9B != null)
                {
                    ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9B);
                }
            }
        }
Beispiel #22
0
    public static void GenerateAndTest(string dataToCrypt)
    {
        /******* Generating keys **********/
        X9ECParameters     ecP    = CustomNamedCurves.GetByName("curve25519");
        ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
        IAsymmetricCipherKeyPairGenerator kpgen = GeneratorUtilities.GetKeyPairGenerator("ECDH");

        kpgen.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));
        AsymmetricCipherKeyPair pairA = kpgen.GenerateKeyPair();
        AsymmetricCipherKeyPair pairB = kpgen.GenerateKeyPair();
        var    PrivateA = pairA.Private;
        var    PublicA  = pairA.Public;
        var    PrivateB = pairB.Private;
        var    PublicB  = pairB.Public;
        string privateA = new string(BytesToHex(SavePrivateKey(PrivateA)));
        string publicA  = new string(BytesToHex(SavePublicKey(PublicA)));

        string privateB = new string(BytesToHex(SavePrivateKey(PrivateB)));
        string publicB  = new string(BytesToHex(SavePublicKey(PublicB)));

        Console.WriteLine("PrvA: " + privateA);
        Console.WriteLine("PubA: " + publicA);
        Console.WriteLine("PrvB: " + privateB);
        Console.WriteLine("PubB: " + publicB);
        /********* Encrypt and decrypt with signature ***********/
        string encrypted = EncryptData(dataToCrypt, privateB, publicA);

        Console.WriteLine("Encrypted : " + encrypted);
        string sign = Sign(encrypted, privateB);

        Console.WriteLine("signature : " + sign);
        bool isSignedCorrect = IsSignCorrect(encrypted, sign, publicB);

        Console.WriteLine("Signature is OK ? " + isSignedCorrect);
        if (isSignedCorrect)
        {
            string decrypted = DecryptData(encrypted, privateA, publicB);
            Console.WriteLine("Is OK " + decrypted.Equals(dataToCrypt));
            Console.WriteLine("decrypted Data : " + decrypted);
        }
        else
        {
            Console.WriteLine("Signature not valid");
        }
    }
Beispiel #23
0
        public X9ECParameters GetCurve()
        {
            CBORObject cborKeyType = m_map[CoseKeyKeys.KeyType];

            if (cborKeyType == null)
            {
                throw new CoseException("Malformed key struture");
            }
            if ((cborKeyType.Type != CBORType.Number) &&
                !((cborKeyType == GeneralValues.KeyType_EC) || (cborKeyType == GeneralValues.KeyType_OKP)))
            {
                throw new CoseException("Not an EC key");
            }

            CBORObject cborCurve = m_map[CoseKeyParameterKeys.EC_Curve];

            if (cborCurve.Type == CBORType.Number)
            {
                switch ((GeneralValuesInt)cborCurve.AsInt32())
                {
                case GeneralValuesInt.P256: return(NistNamedCurves.GetByName("P-256"));

                case GeneralValuesInt.P384: return(NistNamedCurves.GetByName("P-384"));

                case GeneralValuesInt.P521: return(NistNamedCurves.GetByName("P-521"));

                case GeneralValuesInt.X25519: return(CustomNamedCurves.GetByName("CURVE25519"));

                default:
                    throw new CoseException("Unsupported key type: " + cborKeyType.AsInt32());
                }
            }
            else if (cborCurve.Type == CBORType.TextString)
            {
                switch (cborCurve.AsString())
                {
                default:
                    throw new CoseException("Unsupported key type: " + cborKeyType.AsString());
                }
            }
            else
            {
                throw new CoseException("Incorrectly encoded key type");
            }
        }
Beispiel #24
0
        public static ECDomainParameters GetParametersForNamedCurve(int namedCurve)
        {
            string nameOfNamedCurve = GetNameOfNamedCurve(namedCurve);

            if (nameOfNamedCurve == null)
            {
                return(null);
            }
            X9ECParameters byName = CustomNamedCurves.GetByName(nameOfNamedCurve);

            if (byName == null)
            {
                byName = ECNamedCurveTable.GetByName(nameOfNamedCurve);
                if (byName == null)
                {
                    return(null);
                }
            }
            return(new ECDomainParameters(byName.Curve, byName.G, byName.N, byName.H, byName.GetSeed()));
        }
Beispiel #25
0
        // TODO Add an equivalent class for ECNamedCurveParameterSpec?
        //private ECNamedCurveParameterSpec ReadECParameters(
//		private X9ECParameters ReadECParameters(PemObject pemObject)
//		{
//			DerObjectIdentifier oid = (DerObjectIdentifier)Asn1Object.FromByteArray(pemObject.Content);
//
//			//return ECNamedCurveTable.getParameterSpec(oid.Id);
//			return GetCurveParameters(oid.Id);
//		}

        //private static ECDomainParameters GetCurveParameters(
        private static X9ECParameters GetCurveParameters(
            string name)
        {
            // TODO ECGost3410NamedCurves support (returns ECDomainParameters though)

            X9ECParameters ecP = CustomNamedCurves.GetByName(name);

            if (ecP == null)
            {
                ecP = ECNamedCurveTable.GetByName(name);
            }

            if (ecP == null)
            {
                throw new Exception("unknown curve name: " + name);
            }

            //return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
            return(ecP);
        }
Beispiel #26
0
        public void TestAddSubtractMultiplyTwiceEncoding()
        {
            ArrayList names = new ArrayList();

            CollectionUtilities.AddRange(names, ECNamedCurveTable.Names);
            CollectionUtilities.AddRange(names, CustomNamedCurves.Names);

            foreach (string name in names)
            {
                X9ECParameters x9ECParameters = ECNamedCurveTable.GetByName(name);
                if (x9ECParameters != null)
                {
                    ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9ECParameters);
                }

                x9ECParameters = CustomNamedCurves.GetByName(name);
                if (x9ECParameters != null)
                {
                    ImplAddSubtractMultiplyTwiceEncodingTestAllCoords(x9ECParameters);
                }
            }
        }
        private IList GetTestCurves()
        {
            ArrayList x9s   = new ArrayList();
            ISet      names = new HashSet(ECNamedCurveTable.Names);

            names.AddAll(CustomNamedCurves.Names);

            foreach (string name in names)
            {
                X9ECParameters x9 = ECNamedCurveTable.GetByName(name);
                if (x9 != null)
                {
                    AddTestCurves(x9s, x9);
                }

                x9 = CustomNamedCurves.GetByName(name);
                if (x9 != null)
                {
                    AddTestCurves(x9s, x9);
                }
            }
            return(x9s);
        }
        private IList GetTestCurves()
        {
            ArrayList x9s   = new ArrayList();
            ArrayList names = new ArrayList();

            CollectionUtilities.AddRange(names, ECNamedCurveTable.Names);
            CollectionUtilities.AddRange(names, CustomNamedCurves.Names);
            foreach (string name in names)
            {
                X9ECParameters x9 = ECNamedCurveTable.GetByName(name);
                if (x9 != null)
                {
                    AddTestCurves(x9s, x9);
                }

                x9 = CustomNamedCurves.GetByName(name);
                if (x9 != null)
                {
                    AddTestCurves(x9s, x9);
                }
            }
            return(x9s);
        }
        public void TestFixedPointMultiplier()
        {
            FixedPointCombMultiplier M = new FixedPointCombMultiplier();

            ArrayList names = new ArrayList();

            CollectionUtilities.AddRange(names, ECNamedCurveTable.Names);
            CollectionUtilities.AddRange(names, CustomNamedCurves.Names);

            ISet uniqNames = new HashSet(names);

            foreach (string name in uniqNames)
            {
                X9ECParameters x9A = ECNamedCurveTable.GetByName(name);
                X9ECParameters x9B = CustomNamedCurves.GetByName(name);

                X9ECParameters x9 = x9B != null ? x9B : x9A;

                for (int i = 0; i < TestsPerCurve; ++i)
                {
                    BigInteger k    = new BigInteger(x9.N.BitLength, Random);
                    ECPoint    pRef = ECAlgorithms.ReferenceMultiply(x9.G, k);

                    if (x9A != null)
                    {
                        ECPoint pA = M.Multiply(x9A.G, k);
                        AssertPointsEqual("Standard curve fixed-point failure", pRef, pA);
                    }

                    if (x9B != null)
                    {
                        ECPoint pB = M.Multiply(x9B.G, k);
                        AssertPointsEqual("Custom curve fixed-point failure", pRef, pB);
                    }
                }
            }
        }
Beispiel #30
0
        public static EphemeralKeyPair Generate(string curveName)
        {
            var ecp = CustomNamedCurves.GetByName(curveName);
            var ecs = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed());
            var g   = new ECKeyPairGenerator();

            g.Init(new ECKeyGenerationParameters(ecs, new SecureRandom()));

            var pair  = g.GenerateKeyPair();
            var agree = new ECDHBasicAgreement();

            agree.Init(pair.Private);

            var pubkey = MarshalCurvePoint(((ECPublicKeyParameters)pair.Public).Q);
            var done   = new GenerateSharedKeyDelegate(theirPub =>
            {
                var point = UnmarshalCurvePoint(ecp.Curve, theirPub);
                var key   = new ECPublicKeyParameters(point, ecs);

                return(agree.CalculateAgreement(key).ToByteArray());
            });

            return(new EphemeralKeyPair(pubkey, done));
        }