Ejemplo n.º 1
0
        public static byte[] Sign(byte[] bytes, byte[] privateKey)
        {
            var x9EcParameters = SecNamedCurves.GetByName("secp256k1");
            var ecParams       = new ECDomainParameters(x9EcParameters.Curve, x9EcParameters.G, x9EcParameters.N, x9EcParameters.H);

            var privateKeyBigInteger = new BigInteger((new byte[] { 0x00 }).Concat(privateKey).ToArray());

            var signer = new ECDsaSigner();

            var privateKeyParameters = new ECPrivateKeyParameters(privateKeyBigInteger, ecParams);

            signer.Init(true, privateKeyParameters);

            var signature = signer.GenerateSignature(bytes);

            var memoryStream = new MemoryStream();

            var sequenceGenerator = new DerSequenceGenerator(memoryStream);

            sequenceGenerator.AddObject(new DerInteger(signature[0]));
            sequenceGenerator.AddObject(new DerInteger(signature[1]));
            sequenceGenerator.Close();

            var signingResult = memoryStream.ToArray();

            return(signingResult);
        }
Ejemplo n.º 2
0
//		private static readonly Hashtable CurveNames = new Hashtable();
//		private static readonly Hashtable CurveAliases = new Hashtable();
//
//		static NamedCurveTest()
//		{
//			CurveNames.Add("prime192v1", "prime192v1"); // X9.62
//			CurveNames.Add("sect571r1", "sect571r1"); // sec
//			CurveNames.Add("secp224r1", "secp224r1");
//			CurveNames.Add("B-409", SecNamedCurves.GetName(NistNamedCurves.GetOid("B-409")));   // nist
//			CurveNames.Add("P-521", SecNamedCurves.GetName(NistNamedCurves.GetOid("P-521")));
//			CurveNames.Add("brainpoolp160r1", "brainpoolp160r1");         // TeleTrusT
//
//			CurveAliases.Add("secp192r1", "prime192v1");
//			CurveAliases.Add("secp256r1", "prime256v1");
//		}

        private static ECDomainParameters GetCurveParameters(
            string name)
        {
            ECDomainParameters ecdp = ECGost3410NamedCurves.GetByName(name);

            if (ecdp != null)
            {
                return(ecdp);
            }

            X9ECParameters ecP = X962NamedCurves.GetByName(name);

            if (ecP == null)
            {
                ecP = SecNamedCurves.GetByName(name);
                if (ecP == null)
                {
                    ecP = NistNamedCurves.GetByName(name);
                    if (ecP == null)
                    {
                        ecP = TeleTrusTNamedCurves.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()));
        }
Ejemplo n.º 3
0
        private (byte[] PrivateKey, byte[] PublicKey) ReadPem(string pemFile)
        {
            using (var reader = File.OpenText(pemFile))
            {
                var    pemReader = new PemReader(reader);
                object o;
                while ((o = pemReader.ReadObject()) != null)
                {
                    if (o is AsymmetricCipherKeyPair pair)
                    {
                        var privateKeyFromPair = ((ECPrivateKeyParameters)pair.Private).D.ToByteArrayUnsigned();
                        var publicKeyFromPair  = ((ECPublicKeyParameters)pair.Public).Q.GetEncoded();

                        return(PrivateKey : privateKeyFromPair, PublicKey : publicKeyFromPair);
                    }

                    if (o is ECPrivateKeyParameters privateKey)
                    {
                        var curve  = SecNamedCurves.GetByName("secp256r1");
                        var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N);

                        var publicKeyParameters = new ECPublicKeyParameters(domain.G.Multiply(new BigInteger(1, privateKey.D.ToByteArrayUnsigned())), domain);

                        return(PrivateKey : privateKey.D.ToByteArrayUnsigned(), PublicKey : publicKeyParameters.Q.GetEncoded());
                    }

                    if (o is ECPublicKeyParameters publicKey)
                    {
                        return(PrivateKey : null, PublicKey : publicKey.Q.GetEncoded());
                    }
                }

                throw new InvalidOperationException("Key pair was not found in PEM file");
            }
        }
Ejemplo n.º 4
0
        private static ECDsa LoadPrivateKey(string pem)
        {
            var reader     = new PemReader(new StringReader(pem));
            var keyPair    = (AsymmetricCipherKeyPair)reader.ReadObject();
            var p          = (ECPrivateKeyParameters)keyPair.Private;
            var privKeyInt = p.D;
            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();

#if NETSTANDARD2_0
            return(ECDsa.Create(new ECParameters
            {
                Curve = ECCurve.NamedCurves.nistP256,
                D = privKeyInt.ToByteArrayUnsigned(),
                Q = new ECPoint
                {
                    X = privKeyX,
                    Y = privKeyY
                }
            }));
#else
            var x     = EccKey.New(privKeyX, privKeyY, privKeyInt.ToByteArrayUnsigned());
            var ecdsa = new ECDsaCng(x);
            return(ecdsa);
#endif
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Calculates an ECDSA signature in DER format for the given input hash. Note that the input is expected to be
        /// 32 bytes long.
        /// </summary>
        public byte[] Sign(byte[] input, Org.BouncyCastle.Math.BigInteger privateKey)
        {
            const string BITCOIN_CURVE = "secp256k1";
            ECDsaSigner  signer        = new ECDsaSigner();

            Org.BouncyCastle.Asn1.X9.X9ECParameters ecp = SecNamedCurves.GetByName(BITCOIN_CURVE);
            ECDomainParameters EcParameters             = new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H);

            var privateKeyParameters = new ECPrivateKeyParameters(privateKey, EcParameters);

            signer.Init(true, privateKeyParameters);
            var signatures = signer.GenerateSignature(input);

            // What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
            // of the type used by BitCoin we have to encode them using DER encoding, which is just a way to pack the two
            // components into a structure.
            using (var byteOutputStream = new MemoryStream())
            {
                var derSequenceGenerator = new DerSequenceGenerator(byteOutputStream);
                derSequenceGenerator.AddObject(new DerInteger(signatures[0]));
                derSequenceGenerator.AddObject(new DerInteger(signatures[1]));
                derSequenceGenerator.Close();
                return(byteOutputStream.ToArray());
            }
        }
Ejemplo n.º 6
0
        public ECPublicKeyParameters DecodePublicKey(byte[] encodedPublicKey)
        {
            try
            {
                X9ECParameters curve = SecNamedCurves.GetByName("secp256r1");
                ECPoint        point;
                try
                {
                    point = curve.Curve.DecodePoint(encodedPublicKey);
                }
                catch (Exception e)
                {
                    throw new U2fException("Could not parse user public key", e);
                }

                ECPublicKeyParameters xxpk = new ECPublicKeyParameters("ECDSA", point,
                                                                       SecObjectIdentifiers.SecP256r1);

                return(xxpk);
            }
            catch (InvalidKeySpecException e)
            {
                throw new U2fException(ErrorDecodingPublicKey, e);
            }
        }
Ejemplo n.º 7
0
        public static ECPrivateKeyParameters ParsePrivateKey(string keyBytesHex)
        {
            var curve     = SecNamedCurves.GetByName("secp256r1");
            var curveSpec = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            return(new ECPrivateKeyParameters(new BigInteger(keyBytesHex, 16), curveSpec));
        }
Ejemplo n.º 8
0
        static Verifier()
        {
            // Get secp256k1 params.
            X9ECParameters curParams = SecNamedCurves.GetByName("secp256k1");

            _ecParams = new ECDomainParameters(curParams.Curve, curParams.G, curParams.N, curParams.H);
        }
Ejemplo n.º 9
0
        public static byte[] SignTransaction(byte[] data, byte[] privateKey)
        {
            ECDsaSigner        signer = new ECDsaSigner();
            X9ECParameters     spec   = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domain = new ECDomainParameters(spec.Curve, spec.G, spec.N);

            ECPrivateKeyParameters privateKeyParms =
                new ECPrivateKeyParameters(new BigInteger(1, privateKey), domain);
            ParametersWithRandom paramxs = new ParametersWithRandom(privateKeyParms);

            signer.Init(true, paramxs);

            var signature = signer.GenerateSignature(data); //sign and get R and S

            //return as DER format
            using (MemoryStream outStream = new MemoryStream(80))
            {
                DerSequenceGenerator seq = new DerSequenceGenerator(outStream);
                seq.AddObject(new DerInteger(signature[0]));                                                              //r
                seq.AddObject(new DerInteger(signature[1]));                                                              //s
                seq.AddObject(new DerInteger(GetRecoveryId(signature[0].ToByteArray(),
                                                           signature[1].ToByteArray(), data, GetPublicKey(privateKey)))); //v
                seq.Close();
                return(outStream.ToArray());
            }
        }
Ejemplo n.º 10
0
        public ECKeyPair(string privateKeyHex)
        {
            AsymmetricCipherKeyPair keyPair;

            X9ECParameters     Params = SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters Curve  = new ECDomainParameters(Params.Curve, Params.G, Params.N, Params.H);

            BigInteger             bigInteger             = new BigInteger(privateKeyHex, 16);
            ECPrivateKeyParameters ecPrivateKeyParameters = new ECPrivateKeyParameters(bigInteger, Curve);
            var q = Curve.G.Multiply(bigInteger);
            ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(q, Curve);

            ECPublicKey  = ecPublicKeyParameters;
            ECPrivateKey = ecPrivateKeyParameters;

            keyPair = new AsymmetricCipherKeyPair(
                (AsymmetricKeyParameter)ecPublicKeyParameters,
                (AsymmetricKeyParameter)ecPrivateKeyParameters);


            TextWriter writer1    = (TextWriter) new StringWriter();
            PemWriter  pemWriter1 = new PemWriter(writer1);

            pemWriter1.WriteObject((object)keyPair.Private);
            pemWriter1.Writer.Flush();
            this.PrivateKey = writer1.ToString();

            TextWriter writer2    = (TextWriter) new StringWriter();
            PemWriter  pemWriter2 = new PemWriter(writer2);

            pemWriter2.WriteObject((object)keyPair.Public);
            pemWriter2.Writer.Flush();
            this.PublicKey = writer2.ToString();
        }
Ejemplo n.º 11
0
        public static byte[] CreatePublicKeyFromPrivate(byte[] privateKey)
        {
            privateKey = (new byte[]
            {
                0x00
            }).Concat(privateKey).ToArray();

            var secp256K1Algorithm = SecNamedCurves.GetByName("secp256k1");
            var privateKeyInteger  = new BigInteger(privateKey);

            var multiplication = secp256K1Algorithm.G.Multiply(privateKeyInteger).Normalize();
            var publicKey      = new byte[65];

            var y = multiplication.AffineYCoord.ToBigInteger().ToByteArray();

            Array.Copy(y, 0, publicKey, 64 - y.Length + 1, y.Length);

            var x = multiplication.AffineXCoord.ToBigInteger().ToByteArray();

            Array.Copy(x, 0, publicKey, 32 - x.Length + 1, x.Length);

            publicKey[0] = 0x04;

            return(publicKey);
        }
Ejemplo n.º 12
0
        public Packet MessageDecrypt(Packet outer)
        {
            byte[] remoteKeyData      = outer.Body.Take(21).ToArray();
            byte[] ivData             = outer.Body.Skip(21).Take(4).ToArray();
            byte[] innerEncryptedData = outer.Body.Skip(25).Take(outer.Body.Length - 29).ToArray();

            // Decode the body
            ECKeyPair remoteEphemeralKeys = ECKeyPair.LoadKeys(SecNamedCurves.GetByName("secp160r1"), remoteKeyData, null);

            var idAgreement = ECDHAgree(remoteEphemeralKeys.PublicKey, Key.PrivateKey);
            var agreedHash  = Helpers.SHA256Hash(Helpers.ToByteArray(idAgreement, 20));
            var aesKey      = Helpers.FoldOnce(agreedHash);

            // Pad out the IV
            byte[] aesIV = new byte[16];
            Array.Clear(aesIV, 0, 16);
            Buffer.BlockCopy(ivData, 0, aesIV, 0, 4);

            // Decrypt it
            var cipher     = new BufferedBlockCipher(new SicBlockCipher(new AesFastEngine()));
            var parameters = new ParametersWithIV(new KeyParameter(aesKey), aesIV);

            cipher.Init(false, parameters);
            byte[] decryptedBody = new byte[innerEncryptedData.Length];
            var    offset        = cipher.ProcessBytes(innerEncryptedData, decryptedBody, 0);

            cipher.DoFinal(decryptedBody, offset);

            Packet outPacket = Packet.DecodePacket(decryptedBody);

            return(outPacket);
        }
Ejemplo n.º 13
0
        public override (byte[], byte[]) GetChildPrivateKey(Curve curve, byte[] privateKey, byte[] chainCode, uint index)
        {
            byte[] l;

            if ((index & 0x80000000) != 0) // hardened
            {
                l = Bip32Hash(chainCode, index, 0, privateKey);
            }
            else
            {
                if (curve.Kind == ECKind.Ed25519)
                {
                    throw new NotSupportedException("Ed25519 doesn't support non-hardened key derivation");
                }

                l = Bip32Hash(chainCode, index, curve.GetPublicKey(privateKey));
            }

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

            if (curve.Kind == ECKind.Ed25519)
            {
                l.Flush();
                return(ll, lr);
            }

            while (true)
            {
                var parse256LL = new BigInteger(1, ll);
                var kPar       = new BigInteger(1, privateKey);
                var N          = curve.Kind switch
                {
                    ECKind.Secp256k1 => SecNamedCurves.GetByName("secp256k1").N,
                    ECKind.NistP256 => SecNamedCurves.GetByName("secp256r1").N,
                    _ => throw new InvalidEnumArgumentException()
                };
                var key = parse256LL.Add(kPar).Mod(N);

                if (parse256LL.CompareTo(N) >= 0 || key.CompareTo(BigInteger.Zero) == 0)
                {
                    l  = Bip32Hash(chainCode, index, 1, lr);
                    ll = l.GetBytes(0, 32);
                    lr = l.GetBytes(32, 32);
                    continue;
                }

                var keyBytes = key.ToByteArrayUnsigned();
                if (keyBytes.Length < 32)
                {
                    var kb = keyBytes;
                    keyBytes = new byte[32 - kb.Length].Concat(kb);
                    kb.Flush();
                }

                l.Flush();
                ll.Flush();
                return(keyBytes, lr);
            }
        }
Ejemplo n.º 14
0
        public override (byte[], byte[]) GenerateMasterKey(Curve curve, byte[] seed)
        {
            using var hmacSha512 = new HMACSHA512(curve.SeedKey);
            while (true)
            {
                var l  = hmacSha512.ComputeHash(seed);
                var ll = l.GetBytes(0, 32);
                var lr = l.GetBytes(32, 32);

                if (curve.Kind == ECKind.Ed25519)
                {
                    l.Flush();
                    return(ll, lr);
                }

                var parse256LL = new BigInteger(1, ll);
                var N          = curve.Kind switch
                {
                    ECKind.Secp256k1 => SecNamedCurves.GetByName("secp256k1").N,
                    ECKind.NistP256 => SecNamedCurves.GetByName("secp256r1").N,
                    _ => throw new InvalidEnumArgumentException()
                };

                if (parse256LL.CompareTo(N) < 0 && parse256LL.CompareTo(BigInteger.Zero) != 0)
                {
                    l.Flush();
                    return(ll, lr);
                }

                seed = l;
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Generate a signature
        /// Using https://github.com/Zaliro/Switcheo.Net/blob/master/Switcheo.Net/SwitcheoAuthenticationProvider.cs
        /// </summary>
        /// <param name="message">Message to sign</param>
        /// <param name="wallet">Wallet for signature</param>
        /// <returns>Message signature</returns>
        private string GenerateSignature(byte[] message, NeoWallet wallet)
        {
            var privateKey = wallet.privateKey;

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

            var priv     = new ECPrivateKeyParameters("ECDSA", (new BigInteger(1, privateKey)), domain);
            var signer   = new ECDsaSigner();
            var fullsign = new byte[64];

            var hash = new Sha256Digest();

            hash.BlockUpdate(message, 0, message.Length);

            var result = new byte[32];

            hash.DoFinal(result, 0);

            message = result;

            signer.Init(true, priv);
            var signature = signer.GenerateSignature(message);

            var signedResult = ProcessSignature(signature);

            var signedMessage = BitConverter.ToString(signedResult);

            return(signedMessage.Replace("-", "").ToLower());
        }
Ejemplo n.º 16
0
        public static byte[] GeneratePublicKey(byte[] privateKey)
        {
            Org.BouncyCastle.Math.BigInteger privateKeyInt = new Org.BouncyCastle.Math.BigInteger(+1, privateKey);

            var parameters = SecNamedCurves.GetByName("secp256k1");

            Org.BouncyCastle.Math.EC.ECPoint point = parameters.G.Multiply(privateKeyInt);

            byte[] pubKeyX = point.X.ToBigInteger().ToByteArrayUnsigned();
            byte[] pubKeyY = point.Y.ToBigInteger().ToByteArrayUnsigned();

            Console.WriteLine("Your X point on the Elliptic Curve is: " + Encoding.Unicode.GetString(pubKeyX));
            Console.WriteLine("Your Y point on the Elliptic Curve is: " + Encoding.Unicode.GetString(pubKeyY));

            byte[] pubKey = new byte[pubKeyX.Length + 1];

            // Copy pub key X over to pubKey
            pubKeyX.CopyTo(pubKey, 1);

            // Setup the parity byte
            if (point.Y.ToBigInteger().Mod(new Org.BouncyCastle.Math.BigInteger("2")) == new Org.BouncyCastle.Math.BigInteger("1"))
            {
                pubKey[0] = 0x03;
            }
            else
            {
                pubKey[0] = 0x02;
            }

            // Return the public key
            //return Tuple.Create(pubKeyX, pubKeyY);
            return(pubKey);
        }
Ejemplo n.º 17
0
        public ECPublicKeyParameters DecodePublicKey(byte[] encodedPublicKey)
        {
            try
            {
                var curve = SecNamedCurves.GetByName("secp256r1");
                if (curve == null)
                {
                    throw new U2FException("Named curve 'secp256r1' isn't supported");
                }

                ECPoint point;
                try
                {
                    point = curve.Curve.DecodePoint(encodedPublicKey);
                }
                catch (Exception e)
                {
                    throw new U2FException("Couldn't parse user public key", e);
                }

                var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
                return(new ECPublicKeyParameters(point, parameters));
            }
            catch (Exception e)
            {
                throw new U2FException("Error when decoding public key", e);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Parameters to generate the key for
        /// </summary>
        /// <returns></returns>
        private string GetEcCurve()
        {
            var ret = "secp384r1"; // Default

            try
            {
                var config = Properties.Settings.Default.ECCurve;
                DerObjectIdentifier curveOid = null;
                try
                {
                    curveOid = SecNamedCurves.GetOid(config);
                }
                catch {}
                if (curveOid != null)
                {
                    ret = config;
                }
                else
                {
                    _log.Warning("Unknown curve {ECCurve}", config);
                }
            }
            catch (Exception ex)
            {
                _log.Warning("Unable to get EC name, error: {@ex}", ex);
            }
            _log.Debug("ECCurve: {ECCurve}", ret);
            return(ret);
        }
Ejemplo n.º 19
0
        public static void GenerateKey(
            out byte[] privateKey, out byte[] publicKey)
        {
            var rnd = new SecureRandom();

            rnd.SetSeed(DateTime.UtcNow.Ticks);

            var curve = SecNamedCurves.GetByName(CurveName);
            var n     = curve.N;

            BigInteger d;

            do
            {
                d = new BigInteger(n.BitLength, rnd).SetBit(n.BitLength - 1);
            } while (d.CompareTo(n) >= 0);
            privateKey = d.ToByteArrayUnsigned();

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

            publicKey = ToBytes(new ECPoint
            {
                X = pubPoint.XCoord.GetEncoded(),
                Y = pubPoint.YCoord.GetEncoded(),
            });
        }
Ejemplo n.º 20
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 = X962NamedCurves.GetByName(name);

            if (ecP == null)
            {
                ecP = SecNamedCurves.GetByName(name);
                if (ecP == null)
                {
                    ecP = NistNamedCurves.GetByName(name);
                    if (ecP == null)
                    {
                        ecP = TeleTrusTNamedCurves.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);
        }
Ejemplo n.º 21
0
        private static bool VerifySignature(string message, byte[] public_key_bytes, string signature)
        {
            var curve  = SecNamedCurves.GetByName("secp256r1");
            var domain = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);

            //var publicKeyBytes = Base58Encoding.Decode(publicKey);
            //var publicKeyBytes = Base58Encoding.DecodeWithCheckSum(publicKey);
            //var publicKeyBytes = Base58Encoding.DecodePublicKey(publicKey);

            var q = curve.Curve.DecodePoint(public_key_bytes);

            var keyParameters = new
                                Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters(q,
                                                                                         domain);

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

            signer.Init(false, keyParameters);
            signer.BlockUpdate(Encoding.UTF8.GetBytes(message), 0, message.Length);

            var signatureBytes = Base58Encoding.Decode(signature);
            var derSign        = SignatureHelper.derSign(signatureBytes);

            return(signer.VerifySignature(derSign));
        }
Ejemplo n.º 22
0
        /**
         * return a X9ECParameters object representing the passed in named
         * curve. The routine returns null if the curve is not present.
         *
         * @param name the name of the curve requested
         * @return an X9ECParameters object or null if the curve is not available.
         */
        public static X9ECParameters GetByName(string name)
        {
            X9ECParameters ecP = X962NamedCurves.GetByName(name);

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

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

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

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

            return(ecP);
        }
Ejemplo n.º 23
0
        /**
         * return the object identifier signified by the passed in name. Null
         * if there is no object identifier associated with name.
         *
         * @return the object identifier associated with name, if present.
         */
        public static DerObjectIdentifier GetOid(string name)
        {
            DerObjectIdentifier oid = X962NamedCurves.GetOid(name);

            if (oid == null)
            {
                oid = SecNamedCurves.GetOid(name);
            }

            if (oid == null)
            {
                oid = NistNamedCurves.GetOid(name);
            }

            if (oid == null)
            {
                oid = TeleTrusTNamedCurves.GetOid(name);
            }

            if (oid == null)
            {
                oid = AnssiNamedCurves.GetOid(name);
            }

            return(oid);
        }
Ejemplo n.º 24
0
        public static string GetName(DerObjectIdentifier oid)
        {
            string name = X962NamedCurves.GetName(oid);

            if (name == null)
            {
                name = SecNamedCurves.GetName(oid);
            }
            if (name == null)
            {
                name = NistNamedCurves.GetName(oid);
            }
            if (name == null)
            {
                name = TeleTrusTNamedCurves.GetName(oid);
            }
            if (name == null)
            {
                name = AnssiNamedCurves.GetName(oid);
            }
            if (name == null)
            {
                name = ECGost3410NamedCurves.GetName(oid);
            }
            if (name == null)
            {
                name = GMNamedCurves.GetName(oid);
            }
            return(name);
        }
Ejemplo n.º 25
0
        public void TestECNR521bitPrime()
        {
            BigInteger r = new BigInteger("1820641608112320695747745915744708800944302281118541146383656165330049339564439316345159057453301092391897040509935100825960342573871340486684575368150970954");
            BigInteger s = new BigInteger("6358277176448326821136601602749690343031826490505780896013143436153111780706227024847359990383467115737705919410755190867632280059161174165591324242446800763");

            byte[] kData = new BigInteger("cdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", 16).ToByteArrayUnsigned();

            SecureRandom k = FixedSecureRandom.From(kData);

            X9ECParameters     p     = SecNamedCurves.GetByOid(SecObjectIdentifiers.SecP521r1);
            ECDomainParameters spec  = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECCurve            curve = spec.Curve;

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                spec);

            ISigner sgr = SignerUtilities.GetSigner("SHA512withECNR");

            byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

            checkSignature(521, priKey, pubKey, sgr, k, message, r, s);
        }
Ejemplo n.º 26
0
        /**
         * return a X9ECParameters object representing the passed in named
         * curve.
         *
         * @param oid the object id of the curve requested
         * @return an X9ECParameters object or null if the curve is not available.
         */
        public static X9ECParameters GetByOid(DerObjectIdentifier oid)
        {
            X9ECParameters ecP = X962NamedCurves.GetByOid(oid);

            if (ecP == null)
            {
                ecP = SecNamedCurves.GetByOid(oid);
            }

            // NOTE: All the NIST curves are currently from SEC, so no point in redundant OID lookup

            if (ecP == null)
            {
                ecP = TeleTrusTNamedCurves.GetByOid(oid);
            }
            if (ecP == null)
            {
                ecP = AnssiNamedCurves.GetByOid(oid);
            }
            if (ecP == null)
            {
                ecP = FromDomainParameters(ECGost3410NamedCurves.GetByOid(oid));
            }
            if (ecP == null)
            {
                ecP = GMNamedCurves.GetByOid(oid);
            }
            return(ecP);
        }
Ejemplo n.º 27
0
        /// <summary>	Gets shared secret. </summary>
        ///
        /// def get_shared_secret(priv, pub) :
        ///    pub_point  = pub.point()
        ///    priv_point = int(repr(priv),16)
        ///    res     = pub_point * priv_point
        ///    res_hex = '%032x' % res.x()
        ///    return res_hex
        ///
        /// <remarks>	Paul, 26/10/2015. </remarks>
        ///
        /// <returns>	The shared secret. </returns>
        static public byte[] GetSharedSecret(KeyPair priv, PublicKey pub)
        {
            var ps = SecNamedCurves.GetByName("secp256k1");

            BigInteger ipriv    = new BigInteger(1, priv.PrivateKeyBytes);
            ECPoint    pubPoint = pub.GetECPoint();

            ECPoint shared = pubPoint.Multiply(ipriv);

            BigInteger s = shared.X.ToBigInteger();

            byte[] data = s.ToByteArray();

            int leadingZeros = -1;

            while (data[++leadingZeros] == 0)
            {
                ;
            }

            byte[] result = new byte[data.Length - leadingZeros];
            Buffer.BlockCopy(data, leadingZeros, result, 0, result.Length);

            return(result);
        }
Ejemplo n.º 28
0
        private static void Sign(UnsignedTransaction unsignedTransaction, string privateKey, bool isHex, bool addPubKey,
                                 bool forceCompressed = false)
        {
            bool compressed = false;
            var  bytes      = isHex ? privateKey.FromHexString() : GetBytesFromBase58Key(privateKey);

            if (bytes.Length == 33 && bytes[32] == 1)
            {
                compressed = true;
                bytes      = bytes.Take(32).ToArray();
            }

            var privKeyB       = new BigInteger(1, bytes);
            var parms          = SecNamedCurves.GetByName("secp256k1");
            var curve          = new ECDomainParameters(parms.Curve, parms.G, parms.N, parms.H);
            var halfCurveOrder = parms.N.ShiftRight(1);

            var point = curve.G.Multiply(privKeyB);

            if (compressed || forceCompressed)
            {
                point = new FpPoint(curve.Curve, point.X, point.Y, true);
            }

            var publicKey = point.GetEncoded();
            var signer    = new ECDsaSigner();
            var privKey   = new ECPrivateKeyParameters(privKeyB, curve);

            signer.Init(true, privKey);

            foreach (string toSign in unsignedTransaction.ToSign)
            {
                if (addPubKey)
                {
                    unsignedTransaction.PubKeys.Add(publicKey.ToHexString());
                }

                var components = signer.GenerateSignature(toSign.FromHexString());
                var r          = components[0];
                var s          = components[1];

                if (s.CompareTo(halfCurveOrder) > 0)
                {
                    s = curve.N.Subtract(s);
                }

                using (var ms = new MemoryStream())
                    using (var asn = new Asn1OutputStream(ms)) {
                        var seq = new DerSequenceGenerator(asn);
                        seq.AddObject(new DerInteger(r));
                        seq.AddObject(new DerInteger(s));

                        seq.Close();

                        string signedString = ms.ToArray().ToHexString();

                        unsignedTransaction.Signatures.Add(signedString);
                    }
            }
        }
Ejemplo n.º 29
0
        private void randMult(string curveName)
        {
            X9ECParameters spec = SecNamedCurves.GetByName(curveName);

            BigInteger   n      = spec.N;
            ECPoint      g      = (ECPoint)spec.G;
            SecureRandom random = new SecureRandom();             //SecureRandom.getInstance("SHA1PRNG", "SUN");
            BigInteger   k      = new BigInteger(n.BitLength - 1, random);

            ECPoint qMultiply = null;
            long    startTime = DateTimeUtilities.CurrentUnixMs();

            for (int i = 0; i < NUM_ROUNDS; i++)
            {
                qMultiply = g.Multiply(k);
            }
            long endTime = DateTimeUtilities.CurrentUnixMs();

            double avgDuration = (double)(endTime - startTime) / NUM_ROUNDS;

            Console.WriteLine(curveName);
            Console.Write("Millis   : ");
            Console.WriteLine(avgDuration);
            Console.WriteLine();
        }
Ejemplo n.º 30
0
        public string SignMessage(string msg, string privKey)
        {
            //$.checkArgument(text);
            string hashMsg = DoubleHashMessageReverse(msg);

            // Debugging Only
            //Console.WriteLine("Hashed Message: " + hashMsg);
            //Console.WriteLine("Hashed Message in Bytes: " + BitConverter.ToString(Encoding.Unicode.GetBytes(hashMsg)));
            byte[] bytedPrivKey = ConvertToByteArray(privKey);

            // Retrieve the private key in bigint
            BigInteger privateKeyInt = new BigInteger(+1, ConvertToByteArray(privKey));

            // Reconstruct the curve
            X9ECParameters parameters = SecNamedCurves.GetByName("secp256k1");
            //Org.BouncyCastle.Math.EC.ECPoint point = parameters.G.Multiply(privateKeyInt);

            // Setup the signer
            // https://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.crypto.signers.ECDSASigner
            // Cant new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest())); Because Btc doesn't use those..
            ECDsaSigner signer = new ECDsaSigner();

            // Construct the ECDomainParameters
            // https://programtalk.com/java-api-usage-examples/org.bouncycastle.crypto.params.ECDomainParameters/ => How to get the parameters
            ECDomainParameters ecDomainParams = new ECDomainParameters(parameters.Curve, parameters.G, parameters.N, parameters.H);
            ECKeyParameters    keyParams      = new ECPrivateKeyParameters(privateKeyInt, ecDomainParams);

            signer.Init(true, keyParams);
            BigInteger[] signature = signer.GenerateSignature(Encoding.Unicode.GetBytes(hashMsg));

            // https://stackoverflow.com/questions/37572306/verifying-ecdsa-signature-with-bouncy-castle-in-c-sharp
            MemoryStream stream = new MemoryStream();

            //DerOutputStream der = new DerOutputStream(stream);

            try
            {
                //Asn1EncodableVector seq = new Asn1EncodableVector();
                //seq.Add(new DerInteger(signature[0]));
                //seq.Add(new DerInteger(signature[1]));
                //der.WriteObject(new DerSequence(seq));
                DerSequenceGenerator seq = new DerSequenceGenerator(stream);
                seq.AddObject(new DerInteger(signature[0]));
                seq.AddObject(new DerInteger(signature[1]));
                seq.Close();

                byte[] bitResult = stream.ToArray();

                PrintByteArray(bitResult);

                Console.WriteLine("MemoryStream Output: " + BitConverter.ToString(bitResult).Replace("-", string.Empty));

                return(BitConverter.ToString(bitResult).Replace("-", string.Empty));
            }
            catch (IOException e)
            {
                return(e.ToString());
            }
        }