Exemplo n.º 1
0
        static byte[] EncryptPassword(string password, BigInteger sk)
        {
            SHA1Managed hasher = new SHA1Managed();

            byte[] pwdHash = hasher.ComputeHash(Encoding.UTF8.GetBytes(password)); // SHA1 hash of password is computed.

            X9ECParameters spec = SecNamedCurves.GetByName("sect163k1");           // Picking up an elliptic curve.
            BigInteger     N    = spec.N;                                          // Order of group
            ECPoint        G    = spec.G;                                          // Base point
            BigInteger     x    = new BigInteger(pwdHash);

            x = x.Mod(N).Multiply(sk);
            return(G.Multiply(x).GetEncoded());
        }
Exemplo n.º 2
0
        public static string GenerateSecp256k1PublicKey(string privateKey, bool useCompression)
        {
            var        Ecc          = SecNamedCurves.GetByName("secp256k1");
            var        DomainParams = new ECDomainParameters(Ecc.Curve, Ecc.G, Ecc.N, Ecc.H);
            var        bytes        = Hex.Hex2Bytes(privateKey);
            BigInteger d            = new BigInteger(bytes);
            ECPoint    q            = DomainParams.G.Multiply(d);

            q = q.Normalize();
            var     publicParams = new ECPublicKeyParameters(q, DomainParams);
            FpPoint fp           = new FpPoint(Ecc.Curve, q.AffineXCoord, q.AffineYCoord);

            return(Hex.Bytes2Hex(fp.GetEncoded(useCompression)));
        }
Exemplo n.º 3
0
        public override bool Verify(byte[] msg, byte[] sig, byte[] pubKey)
        {
            var digest = Blake2b.GetDigest(msg);
            var r      = sig.GetBytes(0, 32);
            var s      = sig.GetBytes(32, 32);

            var curve      = SecNamedCurves.GetByName("secp256r1");
            var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            var publicKey  = new ECPublicKeyParameters(curve.Curve.DecodePoint(pubKey), parameters);
            var signer     = new ECDsaSigner();

            signer.Init(false, publicKey);
            return(signer.VerifySignature(digest, new BigInteger(1, r), new BigInteger(1, s)));
        }
Exemplo n.º 4
0
        static public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            var random     = new SecureRandom();
            var curve      = SecNamedCurves.GetByName("secp256r1");
            var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(parameters, random);

            ECKeyPairGenerator keygenerator = new ECKeyPairGenerator();

            keygenerator.Init(keyGenerationParameters);

            return(keygenerator.GenerateKeyPair());
        }
Exemplo n.º 5
0
        BigInteger ECDHAgree(byte[] publicKey, byte[] privateKey)
        {
            var domain = SecNamedCurves.GetByName("secp160r1");
            ECDHBasicAgreement     agreement  = new ECDHBasicAgreement();
            BigInteger             privKeyInt = new BigInteger(privateKey);
            ECDomainParameters     parm       = new ECDomainParameters(domain.Curve, domain.G, domain.N);
            ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters(privKeyInt, parm);

            agreement.Init(privKey);
            var pt = Key.Curve.Curve.DecodePoint(publicKey);
            ECPublicKeyParameters pubParams = new ECPublicKeyParameters(pt, parm);

            return(agreement.CalculateAgreement(pubParams));
        }
Exemplo n.º 6
0
        public static void GenerateKeyFromPrivateKey(byte[] privateKey, out byte[] publicKey)
        {
            var curve = SecNamedCurves.GetByName(CurveName);

            BigInteger d = new BigInteger(privateKey); //should I add '00'??

            var pubPoint = curve.G.Multiply(d).Normalize();

            publicKey = ToBytes(new ECPoint
            {
                X = pubPoint.XCoord.GetEncoded(),
                Y = pubPoint.YCoord.GetEncoded(),
            });
        }
Exemplo n.º 7
0
        public void TestECDsaSecP224K1Sha256()
        {
            X9ECParameters p          = SecNamedCurves.GetByName("secp224k1");
            var            parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var            priKey     = new ECPrivateKeyParameters(
                new BigInteger("BE6F6E91FE96840A6518B56F3FE21689903A64FA729057AB872A9F51", 16), // d
                parameters);
            SecureRandom k =
                FixedSecureRandom.From(Hex.Decode("00c39beac93db21c3266084429eb9b846b787c094f23a4de66447efbb3"));

            byte[] m = Hex.Decode("E5D5A7ADF73C5476FAEE93A2C76CE94DC0557DB04CDC189504779117920B896D");

            var dsa = new ECDsaSigner();

            dsa.Init(true, new ParametersWithRandom(priKey, k));

            IBigInteger[] sig = dsa.GenerateSignature(m);

            IBigInteger r = new BigInteger("8163E5941BED41DA441B33E653C632A55A110893133351E20CE7CB75", 16);
            IBigInteger s = new BigInteger("D12C3FC289DDD5F6890DCE26B65792C8C50E68BF551D617D47DF15A8", 16);

            if (!r.Equals(sig[0]))
            {
                Fail("r component wrong." + NewLine
                     + " expecting: " + r + NewLine
                     + " got      : " + sig[0]);
            }

            if (!s.Equals(sig[1]))
            {
                Fail("s component wrong." + NewLine
                     + " expecting: " + s + NewLine
                     + " got      : " + sig[1]);
            }

            // Verify the signature
            var pubKey = new ECPublicKeyParameters(
                parameters.Curve.DecodePoint(
                    Hex.Decode(
                        "04C5C9B38D3603FCCD6994CBB9594E152B658721E483669BB42728520F484B537647EC816E58A8284D3B89DFEDB173AFDC214ECA95A836FA7C")),
                // Q
                parameters);

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(m, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Exemplo n.º 8
0
        public byte[] GetSignature(byte[] messageBytes)
        {
            var curve  = SecNamedCurves.GetByName("secp256k1");
            var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            var keyParameters = new ECPrivateKeyParameters(_privateKey.D, domain);

            ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");

            signer.Init(true, keyParameters);
            signer.BlockUpdate(messageBytes, 0, messageBytes.Length);
            var signature = signer.GenerateSignature();

            return(signature);
        }
Exemplo n.º 9
0
        public bool SignatureIsValid(string signature, string contents, string publicKey)
        {
            var curve          = SecNamedCurves.GetByName("secp256k1");
            var domain         = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            var publicKeyBytes = Base58Encoding.Decode(publicKey);
            var q             = curve.Curve.DecodePoint(publicKeyBytes);
            var keyParameters = new ECPublicKeyParameters(q, domain);

            Org.BouncyCastle.Crypto.ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
            signer.Init(false, keyParameters);
            signer.BlockUpdate(Encoding.ASCII.GetBytes(contents), 0, contents.Length);
            var signatureBytes = Base58Encoding.Decode(signature);

            return(signer.VerifySignature(signatureBytes));
        }
Exemplo n.º 10
0
        public string GeneratePublicKey(string privateKey)
        {
            if (String.IsNullOrWhiteSpace(privateKey))
            {
                throw new FormatException("Empty private key");
            }

            var curve     = SecNamedCurves.GetByName("secp256k1");
            var domain    = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            var d         = new BigInteger(privateKey, 16);
            var q         = domain.G.Multiply(d);
            var publicKey = new ECPublicKeyParameters(q, domain);

            return(Base58Encoding.Encode(publicKey.Q.GetEncoded()));
        }
Exemplo n.º 11
0
        public static bool VerifySignature(string message, string publicKey, string signature)
        {
            var     curve          = SecNamedCurves.GetByName("secp256k1");
            var     domain         = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            var     publicKeyBytes = Base58Encoding.Decode(publicKey);
            var     q             = curve.Curve.DecodePoint(publicKeyBytes);
            var     keyParameters = new ECPublicKeyParameters(q, domain);
            ISigner signer        = SignerUtilities.GetSigner("SHA-256withECDSA");

            signer.Init(false, keyParameters);
            signer.BlockUpdate(Encoding.ASCII.GetBytes(message), 0, message.Length);
            var signatureBytes = Base58Encoding.Decode(signature);

            return(signer.VerifySignature(signatureBytes));
        }
Exemplo n.º 12
0
        public static Key Deserialize(IEnumerable <byte> payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            var c      = SecNamedCurves.GetByName("secp256k1");
            var domain = new ECDomainParameters(c.Curve, c.G, c.N, c.H);

            Org.BouncyCastle.Math.EC.ECCurve curve = domain.Curve;
            Org.BouncyCastle.Math.EC.ECPoint q     = curve.DecodePoint(payload.ToArray());
            var publicKey = new ECPublicKeyParameters(q, domain);

            return(new Key(null, publicKey));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Generates a new random private key.
        /// </summary>
        /// <returns></returns>
        public static string GeneratePrivateKey()
        {
            ECKeyPairGenerator        gen          = new ECKeyPairGenerator();
            SecureRandom              secureRandom = new SecureRandom();
            X9ECParameters            ps           = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters        ecParams     = new ECDomainParameters(ps.Curve, ps.G, ps.N, ps.H);
            ECKeyGenerationParameters keyGenParam  = new ECKeyGenerationParameters(ecParams, secureRandom);

            gen.Init(keyGenParam);

            AsymmetricCipherKeyPair keyPair    = gen.GenerateKeyPair();
            ECPrivateKeyParameters  privateKey = (ECPrivateKeyParameters)keyPair.Private;

            byte[] privateKeyBytes = privateKey.D.ToByteArrayUnsigned();
            return(ByteArrayToString(privateKeyBytes));
        }
Exemplo n.º 14
0
        public Signature Sign(byte[] msg, byte[] prvKey)
        {
            var keyedHash  = Blake2b.GetDigest(msg);
            var curve      = SecNamedCurves.GetByName("secp256r1");
            var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            var key        = new ECPrivateKeyParameters(new BigInteger(prvKey), parameters);
            var signer     = new ECDsaSigner(new HMacDsaKCalculator(new Blake2bDigest(256)));

            signer.Init(true, parameters: key);
            var rs = signer.GenerateSignature(keyedHash);

            var r = rs[0].ToByteArrayUnsigned();
            var s = rs[1].ToByteArrayUnsigned();

            return(new Signature(r.Concat(s), _SignaturePrefix));
        }
Exemplo n.º 15
0
        // Method to generate transaction signature using a privatekey and message
        public static string GetSignature(string privateKey, string message)
        {
            var curve  = SecNamedCurves.GetByName("secp256k1");
            var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            var keyParameters = new ECPrivateKeyParameters(new Org.BouncyCastle.Math.BigInteger(privateKey), domain);

            ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");

            signer.Init(true, keyParameters);
            signer.BlockUpdate(Encoding.ASCII.GetBytes(message), 0, message.Length);

            var signature = signer.GenerateSignature();

            return(Base58Encoding.Encode(signature));
        }
Exemplo n.º 16
0
        /// <summary>Sets up shared parameters. Occurs when a keypair is first generated.</summary>
        private static void Setup()
        {
            // Get the secp256k1 curve parameters:
            X9ECParameters curParams = SecNamedCurves.GetByName("secp256k1");

            _ecParams = new ECDomainParameters(curParams.Curve, curParams.G, curParams.N, curParams.H);

            // Create a generator:
            Generator = new ECKeyPairGenerator();

            // With the params:
            ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(_ecParams, new SecureRandom());

            // Start the generator:
            Generator.Init(keygenParams);
        }
Exemplo n.º 17
0
        public static string signData(string message, string privatekey)
        {
            var bytes         = HexStringToByteArray(privatekey);
            var curve         = SecNamedCurves.GetByName("secp256r1");
            var domain        = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            var keyParameters = new ECPrivateKeyParameters(new Org.BouncyCastle.Math.BigInteger(1, bytes), domain);
            var signer        = SignerUtilities.GetSigner("SHA-256withECDSA");

            signer.Init(true, keyParameters);
            var bytes_message = HexStringToByteArray(message);

            signer.BlockUpdate(bytes_message, 0, bytes_message.Length);
            var signature = signer.GenerateSignature();

            return(ByteArrayToHexString(DSADERtoPlain(signature)));
        }
        public void NoncompliantGetByName(string arg)
        {
            X9ECParameters curve = null;

            // Elliptic curves always have the key length as part of their names. Rule implementation looks for this
            // key length pattern, so that all curves with a key length smaller than 224 will raise an issue
            curve = SecNamedCurves.GetByName("secp192k1");             // Noncompliant {{Use a key length of at least 224 bits for EC cipher algorithm.}}
            curve = SecNamedCurves.GetByName("secp192r1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect163k1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect163r1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect163r2");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect193r1");             // Noncompliant
            curve = SecNamedCurves.GetByName("sect193r2");             // Noncompliant

            curve = X962NamedCurves.GetByName("prime192v1");           // Noncompliant
            curve = X962NamedCurves.GetByName("prime192v2");           // Noncompliant
            curve = X962NamedCurves.GetByName("prime192v3");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb163v1");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb163v2");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb163v3");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb176w1");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2tnb191v1");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2tnb191v2");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2tnb191v3");           // Noncompliant
            curve = X962NamedCurves.GetByName("c2pnb208w1");           // Noncompliant

            curve = TeleTrusTNamedCurves.GetByName("brainpoolp160r1"); // Noncompliant
            curve = TeleTrusTNamedCurves.GetByName("brainpoolp160t1"); // Noncompliant
            curve = TeleTrusTNamedCurves.GetByName("brainpoolp192r1"); // Noncompliant
            curve = TeleTrusTNamedCurves.GetByName("brainpoolp192t1"); // Noncompliant

            curve = NistNamedCurves.GetByName("B-163");                // Noncompliant
            curve = NistNamedCurves.GetByName("K-163");                // Noncompliant
            curve = NistNamedCurves.GetByName("P-192");                // Noncompliant

            curve = ECNamedCurveTable.GetByName("secp192k1");          // Noncompliant
            curve = ECNamedCurveTable.GetByName("c2pnb208w1");         // Noncompliant
            curve = ECNamedCurveTable.GetByName("brainpoolp192t1");    // Noncompliant
            curve = ECNamedCurveTable.GetByName("B-163");              // Noncompliant

            ECNamedCurveTable.GetByName(arg);                          // Compliant
            var variable = "RandomString";

            ECNamedCurveTable.GetByName(variable);  // Compliant
            variable = "B-163";
            ECNamedCurveTable.GetByName(variable);  // Noncompliant
        }
Exemplo n.º 19
0
        private string GenerateKey()
        {
            ECKeyPairGenerator        gen                     = new ECKeyPairGenerator();
            SecureRandom              secureRandom            = new SecureRandom();
            X9ECParameters            curve                   = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters        domainParameters        = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters(domainParameters, secureRandom);

            gen.Init(keyGenerationParameters);

            AsymmetricCipherKeyPair keyPair = gen.GenerateKeyPair();

            ECPrivateKeyParameters privateKeyParameters = (ECPrivateKeyParameters)keyPair.Private;

            byte[] privateKeyBytes = privateKeyParameters.D.ToByteArrayUnsigned();
            return(this.ByteArrayToString(privateKeyBytes));
        }
        public static string GeneratePkcs10
            (PrivateKey privKey, PublicKey pubKey, string commonName, string organization, string organizationUnit, string city, string state,
            string countryIso2Characters, string email)
        {
            try
            {
                Org.BouncyCastle.Math.BigInteger d = new Org.BouncyCastle.Math.BigInteger(privKey.ByteArray.Reverse().ToArray());

                SecureRandom       secureRandom = new SecureRandom();
                X9ECParameters     curve        = SecNamedCurves.GetByName("secp256k1");
                ECDomainParameters domain       = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

                Org.BouncyCastle.Math.EC.ECPoint q = domain.G.Multiply(d);

                var priv = new ECPrivateKeyParameters("EC", d, SecObjectIdentifiers.SecP256k1);
                var pub  = new ECPublicKeyParameters("EC", q, SecObjectIdentifiers.SecP256k1);

                Dictionary <DerObjectIdentifier, string> attrs = new Dictionary <DerObjectIdentifier, string>();

                attrs.Add(X509Name.O, organization);
                attrs.Add(X509Name.OU, organizationUnit);
                attrs.Add(X509Name.EmailAddress, email);
                attrs.Add(X509Name.L, city);
                attrs.Add(X509Name.ST, state);
                attrs.Add(X509Name.C, countryIso2Characters);
                attrs.Add(X509Name.CN, commonName);

                var subject = new X509Name(attrs.Keys.ToList(), attrs.Values.ToList());

                var pkcs10CertificationRequest = new Pkcs10CertificationRequest("SHA1withECDSA", subject, pub, null, priv);
                var base64csr = Convert.ToBase64String(pkcs10CertificationRequest.GetEncoded());

                var width = 64;
                for (int i = width; i < base64csr.Length; i += width + 1)
                {
                    base64csr = base64csr.Insert(i, "\n");
                }

                return(base64csr);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Called by TLS server to create his ephemeral keys.
        /// TODO: get information about which ECC curve should be used
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public override byte[] GetServerKeys(ProtocolVersion version, CertificatePrivateKey certPrivateKey)
        {
            var ms        = new MemoryStream(certPrivateKey.KeyValue);
            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StreamReader(ms));
            var keyParam  = pemReader.ReadObject();
            var key       = keyParam as AsymmetricCipherKeyPair;
            var pk        = key.Public as ECPublicKeyParameters;
            var certCurve = pk.Q.Curve;

            string curveName = string.Empty;

            for (int i = 0; i < knownCurveNames.Length; i++)
            {
                var curveParams = SecNamedCurves.GetByName(knownCurveNames[i]);
                if (certCurve.GetHashCode() == curveParams.Curve.GetHashCode())
                {
                    curveName = knownCurveNames[i];
                    break;
                }
            }

            if (curveName == string.Empty)
            {
                throw new InvalidOperationException("Could not find EC curve for server private key");
            }

            this.logger?.Debug("Getting server keys for curve '{0}'.", curveName);
            this.GenerateKeys(curveName);

            byte[] pubKeyBytes    = this.publicKey.Q.GetEncoded();
            byte[] serverKeyBytes = new byte[4 + pubKeyBytes.Length];
            serverKeyBytes[0] = 3;

            // get named curve for curve id
            if (Enum.TryParse <EccNamedCurve>(curveName, true, out var curve) == false)
            {
                throw new InvalidOperationException("Could not find named curve for: " + curveName);
            }
            serverKeyBytes[2] = (byte)curve;

            serverKeyBytes[3] = (byte)pubKeyBytes.Length;
            Buffer.BlockCopy(pubKeyBytes, 0, serverKeyBytes, 4, pubKeyBytes.Length);

            return(serverKeyBytes);
        }
        public AsymmetricCipherKeyPair GenerateKeyPair()
        {
            var curve        = SecNamedCurves.GetByName("secp256r1");
            var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

            var secureRandom = new SecureRandom();
            var keyParams    = new ECKeyGenerationParameters(domainParams, secureRandom);

            var generator = new ECKeyPairGenerator("EC");

            generator.Init(keyParams);
            var keyPair = generator.GenerateKeyPair();

            var privateKey = keyPair.Private as ECPrivateKeyParameters;
            var publicKey  = keyPair.Public as ECPublicKeyParameters;

            return(keyPair);
        }
Exemplo n.º 23
0
        public byte[] GetPubKeyFromPrivKey(
            string privKey)
        {
            var curve = SecNamedCurves.GetByName("secp256k1");

            var domain = new ECDomainParameters(
                curve.Curve,
                curve.G,
                curve.N,
                curve.H);

            var d = new Org.BouncyCastle.Math.BigInteger(privKey);
            var q = domain.G.Multiply(d);

            var publicKey = new ECPublicKeyParameters(q, domain);

            return(publicKey.Q.GetEncoded());
        }
Exemplo n.º 24
0
        public Tuple <ECPrivateKeyParameters, ECPublicKeyParameters> CreateKeyPair()
        {
            var curve            = SecNamedCurves.GetByName("secp256k1");
            var domainParameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

            var generator = new ECKeyPairGenerator();

            generator.Init(new ECKeyGenerationParameters(domainParameters, new SecureRandom()));
            var keyPair = new MethodTimer(false).Time("GenerateKeyPair", () => generator.GenerateKeyPair());

            var privateKey = (ECPrivateKeyParameters)keyPair.Private;
            var publicKey  = (ECPublicKeyParameters)keyPair.Public;

            //Debug.WriteLine("Private:  {0}".Format2(privateKey.D.ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Public X: {0}".Format2(publicKey.Q.X.ToBigInteger().ToHexNumberStringUnsigned()));
            //Debug.WriteLine("Public Y: {0}".Format2(publicKey.Q.Y.ToBigInteger().ToHexNumberStringUnsigned()));

            return(Tuple.Create(privateKey, publicKey));
        }
Exemplo n.º 25
0
        public static ECDsa LoadPrivateKey(byte[] key)
        {
            var privKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, key);
            var parameters = SecNamedCurves.GetByName("secp256r1");
            var ecPoint    = parameters.G.Multiply(privKeyInt);
            var privKeyX   = ecPoint.Normalize().XCoord.ToBigInteger().ToByteArrayUnsigned();
            var privKeyY   = ecPoint.Normalize().YCoord.ToBigInteger().ToByteArrayUnsigned();

            return(ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = privKeyInt.ToByteArrayUnsigned(),
                Q = new ECPoint
                {
                    X = privKeyX,
                    Y = privKeyY
                }
            }));
        }
Exemplo n.º 26
0
        private void GenerateKeys(string curveName)
        {
            X9ECParameters ecParams = SecNamedCurves.GetByName(curveName);

            _domainParameters = new ECDomainParameters(ecParams.Curve,
                                                       ecParams.G, ecParams.N, ecParams.H,
                                                       ecParams.GetSeed());
            ECKeyGenerationParameters keyGenParams =
                new ECKeyGenerationParameters(_domainParameters, new SecureRandom());

            AsymmetricCipherKeyPair keyPair;
            ECKeyPairGenerator      generator = new ECKeyPairGenerator();

            generator.Init(keyGenParams);
            keyPair = generator.GenerateKeyPair();

            _privateKey = (ECPrivateKeyParameters)keyPair.Private;
            _publicKey  = (ECPublicKeyParameters)keyPair.Public;
        }
Exemplo n.º 27
0
        public static Identity Generate()
        {
            var ret = new Identity
            {
                DateEpoch = Convert.ToUInt32((DateTime.UtcNow - new DateTime(1970, 01, 01, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds)
            };

            // Elliptic Curve
            var ec = SecNamedCurves.GetByName("secp256k1");

            Debug.Assert(ec != null, "ec != null");
            var domainParams = new ECDomainParameters(ec.Curve, ec.G, ec.N, ec.H);
            var random       = new SecureRandom();

            var keyGen    = new ECKeyPairGenerator();
            var keyParams = new ECKeyGenerationParameters(domainParams, random);

            keyGen.Init(keyParams);
            var keyPair = keyGen.GenerateKeyPair();

            Debug.Assert(keyPair != null, "keyPair != null");
            var privateKeyParams = keyPair.Private as ECPrivateKeyParameters;
            var publicKeyParams  = keyPair.Public as ECPublicKeyParameters;

            // Get Private Key
            Debug.Assert(privateKeyParams != null, "privateKeyParams != null");
            var privD = privateKeyParams.D;

            Debug.Assert(privD != null, "privD != null");
            ret.PrivateKey = privD.ToByteArray();

            Debug.Assert(publicKeyParams != null, "publicKeyParams != null");
            var qa = ec.G.Multiply(privD);

            Debug.Assert(qa != null, "qa != null");
            Debug.Assert(qa.X != null, "qa.X != null");
            ret.PublicKeyX = qa.X.ToBigInteger().ToByteArrayUnsigned();
            Debug.Assert(qa.Y != null, "qa.Y != null");
            ret.PublicKeyY = qa.Y.ToBigInteger().ToByteArrayUnsigned();

            return(ret);
        }
Exemplo n.º 28
0
        public override (byte[], byte[]) GetChildPublicKey(Curve curve, byte[] pubKey, byte[] chainCode, uint index)
        {
            if (curve.Kind == ECKind.Ed25519)
            {
                throw new NotSupportedException("Ed25519 public key derivation not supported by slip-10");
            }
            if (pubKey.Length != 33)
            {
                throw new NotSupportedException("Invalid public key size (expected 33 bytes)");
            }
            if ((index & 0x80000000) != 0)
            {
                throw new InvalidOperationException("Can't derive a hardened child key from a public key");
            }

            var c = curve.Kind switch
            {
                ECKind.Secp256k1 => SecNamedCurves.GetByName("secp256k1"),
                ECKind.NistP256 => SecNamedCurves.GetByName("secp256r1"),
                _ => throw new InvalidEnumArgumentException()
            };
            var dp = new ECDomainParameters(c.Curve, c.G, c.N, c.H, c.GetSeed());
            var kp = new ECPublicKeyParameters("EC", c.Curve.DecodePoint(pubKey), dp);
            var l  = Bip32Hash(chainCode, index, pubKey);

            while (true)
            {
                var ll = l.GetBytes(0, 32);
                var lr = l.GetBytes(32, 32);

                var parse256LL = new BigInteger(1, ll);
                var q          = kp.Parameters.G.Multiply(parse256LL).Add(kp.Q);

                if (parse256LL.CompareTo(c.N) >= 0 || q.IsInfinity)
                {
                    l = Bip32Hash(chainCode, index, 1, lr);
                    continue;
                }

                return(q.Normalize().GetEncoded(true), lr);
            }
        }
Exemplo n.º 29
0
        internal static ECDomainParameters GetECParameters(NamedCurve namedCurve)
        {
            if (!Enum.IsDefined(typeof(NamedCurve), namedCurve))
            {
                return(null);
            }

            string curveName = namedCurve.ToString();

            // Lazily created the first time a particular curve is accessed
            X9ECParameters ecP = SecNamedCurves.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()));
        }
Exemplo n.º 30
0
        public override Signature Sign(byte[] msg, byte[] prvKey)
        {
            var curve      = SecNamedCurves.GetByName("secp256k1");
            var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            var privateKey = new ECPrivateKeyParameters(new BigInteger(1, prvKey), parameters);
            var signer     = new ECDsaSigner(new HMacDsaKCalculator(new Blake2bDigest(256)));

            signer.Init(true, privateKey);
            var rs = signer.GenerateSignature(Blake2b.GetDigest(msg));

            if (rs[1].CompareTo(curve.N.Divide(BigInteger.Two)) > 0)
            {
                rs[1] = curve.N.Subtract(rs[1]);
            }

            var r = rs[0].ToByteArrayUnsigned().Align(32);
            var s = rs[1].ToByteArrayUnsigned().Align(32);

            return(new Signature(r.Concat(s), SignaturePrefix));
        }