VerifySignature() public method

public VerifySignature ( byte message, BigInteger r, BigInteger s ) : bool
message byte
r Org.BouncyCastle.Math.BigInteger
s Org.BouncyCastle.Math.BigInteger
return bool
Example #1
0
 public bool VerifySignature(byte[] hash, byte[] signature)
 {
     ECDsaSigner signer = new ECDsaSigner();
     ECDSASignature parsedSignature = ECDSASignature.FromDER(signature);
     signer.Init(false, key);
     return signer.VerifySignature(hash, parsedSignature.R, parsedSignature.S);
 }
		public Boolean verifySignature(Byte[] data, Byte[] sig)
		{
			ECDsaSigner signer = new ECDsaSigner();
			signer.Init(false, new ECPublicKeyParameters(ecParams.Curve.DecodePoint(pubKey), ecParams));
			using (Asn1InputStream asn1stream = new Asn1InputStream(sig))
			{
				Asn1Sequence seq = (Asn1Sequence)asn1stream.ReadObject();
				return signer.VerifySignature(data, ((DerInteger)seq[0]).PositiveValue, ((DerInteger)seq[1]).PositiveValue);
			}
		}
Example #3
0
 public static bool Verify(byte[] data, byte[] sigBytes, BigInteger pub)
 {
     EcdsaSignature signature = EcdsaSignature.DecodeFromDer(sigBytes);
     var signer = new ECDsaSigner();
     ECPoint pubPoint = Secp256K1.Curve().DecodePoint(pub.ToByteArray());
     var parameters = new ECPublicKeyParameters(pubPoint, Secp256K1.Params());
     signer.Init(false, parameters);
     try
     {
         return signer.VerifySignature(data, signature.R, signature.S);
     }
     catch (Exception)
     {
         return false;
     }
 }
Example #4
0
        public void TestECDsa192bitPrime()
        {
            BigInteger r = new BigInteger("3342403536405981729393488334694600415596881826869351677613");
            BigInteger s = new BigInteger("5735822328888155254683894997897571951568553642892029982342");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("6140507067065001063065065565667405560006161556565665656654"));

            SecureRandom k = FixedSecureRandom.From(kData);

            FpCurve curve = new FpCurve(
                new BigInteger("6277101735386680763835789423207666416083908700390324961279"), // q
                new BigInteger("fffffffffffffffffffffffffffffffefffffffffffffffc", 16), // a
                new BigInteger("64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("03188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012")), // G
                new BigInteger("6277101735386680763835789423176059013767194773182842284081")); // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("651056770906015076056810763456358567190100156695615665659"), // d
                parameters);

            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ECDsaSigner ecdsa = new ECDsaSigner();

            ecdsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecdsa.GenerateSignature(message);

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

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

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("0262b12d60690cdcf330babab6e69763b471f994dd702d16a5")), // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("verification fails");
            }
        }
Example #5
0
        public void TestECDsa191bitBinary()
        {
            BigInteger r = new BigInteger("87194383164871543355722284926904419997237591535066528048");
            BigInteger s = new BigInteger("308992691965804947361541664549085895292153777025772063598");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("1542725565216523985789236956265265265235675811949404040041"));

            SecureRandom k = FixedSecureRandom.From(kData);

            F2mCurve curve = new F2mCurve(
                191, // m
                9, //k
                new BigInteger("2866537B676752636A68F56554E12640276B649EF7526267", 16), // a
                new BigInteger("2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("0436B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D765BE73433B3F95E332932E70EA245CA2418EA0EF98018FB")), // G
                new BigInteger("1569275433846670190958947355803350458831205595451630533029"), // n
                BigInteger.Two); // h

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("1275552191113212300012030439187146164646146646466749494799"), // d
                parameters);

            ECDsaSigner ecdsa = new ECDsaSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecdsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecdsa.GenerateSignature(message);

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

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

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("045DE37E756BD55D72E3768CB396FFEB962614DEA4CE28A2E755C0E0E02F5FB132CAF416EF85B229BBB8E1352003125BA1")), // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Example #6
0
 internal bool Verify(uint256 hash, ECDSASignature sig)
 {
     var signer = new ECDsaSigner();
     signer.Init(false, GetPublicKeyParameters());
     return signer.VerifySignature(hash.ToBytes(), sig.R, sig.S);
 }
Example #7
0
        public bool AreBlocksValid()
        {
            //invalid transactions or incorrect hash value check
            foreach (var b in Blocks)
            {
                if (!b.IsValid())
                {
                    return false;
                }
            }
            //hashchain check
            for (int i = 1; i < Blocks.Count; ++i)
            {
                if (!Enumerable.SequenceEqual(Blocks[i].data.prevHash, Blocks[i].data.prevHash))
                {
                    return false;
                }
            }
            //double-spending checks
            List<RegisterRecord> register = new List<RegisterRecord>();
            for (int i = 1; i < Blocks.Count; ++i)
            {
                if (Blocks[i].data.register.Length > register.Count)
                {
                    for (int j = 0; j < register.Count; ++j)
                    {
                        if (!Blocks[i].data.register[j].address.Equals(register[i].address))
                        {
                            return false;
                        }
                    }
                    for (int j = register.Count; j < Blocks[i].data.register.Length; j++)
                    {
                        register.Add(new RegisterRecord() { address = Blocks[i].data.register[j].address, amount = 0});
                    }
                }
                for (int j = 0; j < Blocks[i].data.transactionsList.Length; ++j)
                {
                    //validating transactions
                    if (!register.Exists(it => it.address.Equals(Blocks[i].data.transactionsList[j].t.reciever)))
                    {
                        return false;
                    }
                    //check existance of pseudonyms in this block's register

                    var signatureChecker = new ECDsaSigner();
                    signatureChecker.Init(false, Account.pemDecodeKey(Blocks[i].data.transactionsList[j].senderPublicKey));
                    if (!signatureChecker.VerifySignature(Blocks[i].data.transactionsList[j].t.getBytes,
                        new BigInteger(Blocks[i].data.transactionsList[j].r), new BigInteger(Blocks[i].data.transactionsList[j].s)))
                    {
                        return false;
                    }
                    //check signature

                    var item = register.Find(it => it.address.Equals(Blocks[i].data.transactionsList[j].t.sender));
                    item.amount -= Blocks[i].data.transactionsList[j].t.money;
                    item = register.Find(it => it.address.Equals(Blocks[i].data.transactionsList[j].t.reciever));
                    item.amount += Blocks[i].data.transactionsList[j].t.money;
                    //proccess
                }
                var finder = register.Find(it => it.address.Equals(Blocks[i].data.finderAddress));
                finder.amount += 25;
                for (int j = 0; j < Blocks[i].data.register.Length; ++j)
                {
                    if (!register[j].address.Equals(Blocks[i].data.register[j].address) && register[j].amount != Blocks[i].data.register[j].amount)
                    {
                        Console.WriteLine("calc");
                        return false;
                    }
                }
                //check state of register
            }
            //admittedly, quite slow
            //TODO: make it faster, use Dictionary (map, in a more meaningful language)
            return true;
        }
Example #8
0
        public void TestECDsaSecP224k1Sha256()
        {
            X9ECParameters p = SecNamedCurves.GetByName("secp224k1");
            ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("BE6F6E91FE96840A6518B56F3FE21689903A64FA729057AB872A9F51", 16), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(Hex.Decode("00c39beac93db21c3266084429eb9b846b787c094f23a4de66447efbb3"));

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

            ECDsaSigner dsa = new ECDsaSigner();

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

            BigInteger[] sig = dsa.GenerateSignature(M);

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

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

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

            // Verify the signature
            ECPublicKeyParameters 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");
            }
        }
Example #9
0
        public void TestECDsaP256Sha256()
        {
            X9ECParameters p = NistNamedCurves.GetByName("P-256");
            ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335")));

            byte[] M = Hex.Decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD");

            ECDsaSigner dsa = new ECDsaSigner();

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

            BigInteger[] sig = dsa.GenerateSignature(M);

            BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384");
            BigInteger s = new BigInteger("98506158880355671805367324764306888225238061309262649376965428126566081727535");

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

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

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

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(M, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Example #10
0
        public void TestECDsaKeyGenTest()
        {
            SecureRandom random = new SecureRandom();

            FpCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n

            ECKeyPairGenerator pGen = new ECKeyPairGenerator();
            ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
                parameters,
                random);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);

            ECDsaSigner ecdsa = new ECDsaSigner();

            ecdsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecdsa.GenerateSignature(message);

            ecdsa.Init(false, pair.Public);

            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        public override byte[] SignData(ProtocolVersion version, byte[] data, HashAlgorithm hashAlgorithm, CertificatePrivateKey privateKey)
        {
            var ms = new MemoryStream(privateKey.KeyValue);
            var pemReader = new PemReader(new StreamReader(ms));
            var keyParam = pemReader.ReadObject();
            var key = keyParam as AsymmetricCipherKeyPair;
            
            var signer = new ECDsaSigner();
            signer.Init(true, key.Private);
            var hashedData = hashAlgorithm.ComputeHash(data);
            Log.Trace("Hashing data (S):" + BitConverter.ToString(data));
            Log.Trace("Hashed data (S):" + BitConverter.ToString(hashedData));

            var sig = signer.GenerateSignature(hashedData);
            
            // test verify
            var _tmpEcPubkey = key.Public as ECPublicKeyParameters;
            Log.Debug("Associated PubKey Q: " + BitConverter.ToString(_tmpEcPubkey.Q.GetEncoded()));
            var signerTest = new ECDsaSigner();
            signerTest.Init(false, key.Public);
            var result = signerTest.VerifySignature(hashedData, sig[0], sig[1]);
            if (!result)
            {
                throw new CryptographicUnexpectedOperationException("Invalid!!!");
            }

            Log.Debug("R value: " + sig[0].SignValue + " " + sig[0].LongValue);
            Log.Debug("S value: " + sig[1].SignValue + " " + sig[1].LongValue);
            // TODO: check how BigIntegers are encoded before sent over the wire
            // Maybe DER encoding of R and S as integer would do it. However for the moment it works with stuffing 0x00 in.
            var rl = new List<byte>(sig[0].ToByteArray());
            var sl = new List<byte>(sig[1].ToByteArray());
            while (rl.Count < 33)
            {
                rl.Insert(0, 0x00);
            }

            while (sl.Count < 33)
            {
                sl.Insert(0, 0x00);
            }
            var r = rl.ToArray();
            var s = sl.ToArray();
            var rs = new byte[r.Length + s.Length];
            Buffer.BlockCopy(r, 0, rs, 0, r.Length);
            Buffer.BlockCopy(s, 0, rs, r.Length, s.Length);
            
            var derSig = DEREncodeSignature(rs);
            // Log.Debug("DER Signature (S): " + BitConverter.ToString(derSig));
            Log.Trace("Signature R (S)" + BitConverter.ToString(r));
            Log.Trace("Signature S (S)" + BitConverter.ToString(s));
            return derSig;
        }
        public override bool VerifyData(ProtocolVersion version, byte[] data, HashAlgorithm hashAlgorithm, CertificatePublicKey publicKey, byte[] signature)
        {
            if (!CertificateKeyAlgorithm.Equals(publicKey.Oid))
            {
                throw new Exception("ECDSA signature verification requires ECDSA public key");
            }

            // Decode the public key parameters
            string curveOid = DER2OID(publicKey.Parameters);
            if (curveOid == null)
            {
                throw new Exception("Unsupported ECDSA public key parameters");
            }

            // Get parameters from the curve OID
            X9ECParameters ecParams = SecNamedCurves.GetByOid(new DerObjectIdentifier(curveOid));
            if (ecParams == null)
            {
                throw new Exception("Unsupported ECC curve type OID: " + curveOid);
            }

            // Construct domain parameters
            ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve,
                                                                         ecParams.G, ecParams.N, ecParams.H,
                                                                         ecParams.GetSeed());

            // Decode the public key data
            byte[] ecPointData = publicKey.KeyValue;
            if (ecPointData[0] != 0x04)
            {
                throw new Exception("Only uncompressed ECDSA keys supported, format: " + ecPointData[0]);
            }
            ECPoint ecPoint = domainParameters.Curve.DecodePoint(ecPointData);
            ECPublicKeyParameters theirPublicKey = new ECPublicKeyParameters(ecPoint, domainParameters);
            
            // Hash input data buffer
            byte[] dataHash;
            if (hashAlgorithm == null)
            {
                dataHash = TLSv1HashData(data);
            }
            else
            {
                dataHash = hashAlgorithm.ComputeHash(data);
            }

            // Actually verify the signature
            BigInteger[] sig = DERDecodeSignature(signature);
            var r = sig[0];
            var s = sig[1];
            Log.Trace("Hashed data (V): " + BitConverter.ToString(dataHash));
            Log.Trace("Public Key Q (V): " + BitConverter.ToString(theirPublicKey.Q.GetEncoded()));
            Log.Trace("Signature R (V): " + BitConverter.ToString(r.ToByteArrayUnsigned()));
            Log.Trace("Signature S (V): " + BitConverter.ToString(s.ToByteArrayUnsigned()));
            Log.Trace("R value: " + sig[0].SignValue + " " + sig[0].LongValue);
            Log.Trace("S value: " + sig[1].SignValue + " " + sig[1].LongValue);


            ECDsaSigner signer = new ECDsaSigner();
            signer.Init(false, theirPublicKey);
            var result = signer.VerifySignature(dataHash, r, s);
            Log.Debug("Signature verification status: {0}.", result);
            return result;
        }
Example #13
0
 public bool Verify(byte[] message, BigInteger r, BigInteger s)
 {
     var signer = new ECDsaSigner();
     signer.Init(false, this.keyPair.Public);
     return signer.VerifySignature(message, r, s);
 }
Example #14
0
		private void btnStartECDSA_Click (object sender, EventArgs e)
		{
			byte[] hash = new byte[160 >> 3];
			Stopwatch sw = new Stopwatch ();
			double ocSignTime, ocVerifyTime, bcSignTime, bcVerifyTime;
			{
				ECDSA ecdsa = new ECDSA (ECDomainNames.secp192r1);
				ecdsa.ToXmlString (false);
				sw.Reset ();
				sw.Start ();
				byte[] ecdsaSign = ecdsa.SignHash (hash);
				sw.Stop ();
				ocSignTime = sw.Elapsed.TotalSeconds;
				sw.Reset ();
				sw.Start ();
				ecdsa.VerifyHash (hash, ecdsaSign);
				sw.Stop ();
				ocVerifyTime = sw.Elapsed.TotalSeconds;
			}

			{
				ECDsaSigner ecdsa = new ECDsaSigner ();
				X9ECParameters SEC_P192r1 = SecNamedCurves.GetByName ("secp192r1");
				BigInteger key = new BigInteger (SEC_P192r1.N.BitCount, new Random ());
				ECDomainParameters domain = new ECDomainParameters (SEC_P192r1.Curve, SEC_P192r1.G, SEC_P192r1.N);
				ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters (key, domain);
				ECPoint publicKeyPoint = SEC_P192r1.G.Multiply (key);
				ECPublicKeyParameters publicKey = new ECPublicKeyParameters (publicKeyPoint, domain);
				ecdsa.Init (true, privateKey);

				sw.Reset ();
				sw.Start ();
				BigInteger[] sign = ecdsa.GenerateSignature (hash);
				sw.Stop ();
				bcSignTime = sw.Elapsed.TotalSeconds;

				ecdsa.Init (false, publicKey);
				sw.Reset ();
				sw.Start ();
				ecdsa.VerifySignature (hash, sign[0], sign[1]);
				sw.Stop ();
				bcVerifyTime = sw.Elapsed.TotalSeconds;
			}

			double scale = 1000;
			bcSignTime *= scale;
			bcVerifyTime *= scale;
			ocSignTime *= scale;
			ocVerifyTime *= scale;

			lblBCSign.Text = "Sign (" + bcSignTime.ToString ("f2") + "ms)";
			lblBCVerify.Text = "Verify (" + bcVerifyTime.ToString ("f2") + "ms)";
			lblOCSign.Text = "Sign (" + ocSignTime.ToString ("f2") + "ms)";
			lblOCVerify.Text = "Verify (" + ocVerifyTime.ToString ("f2") + "ms)";

			double max = Math.Max (ocSignTime, Math.Max (ocVerifyTime, Math.Max (bcSignTime, bcVerifyTime)));			
			max *= 1.1;

			pbEcdsaSignBC.Maximum = pbEcdsaVerifyBC.Maximum = pbEcdsaSignOC.Maximum = pbEcdsaVerifyOC.Maximum = (int)max;
			pbEcdsaSignBC.Value = (int)bcSignTime;
			pbEcdsaVerifyBC.Value = (int)bcVerifyTime;
			pbEcdsaSignOC.Value = (int)ocSignTime;
			pbEcdsaVerifyOC.Value = (int)ocVerifyTime;
		}
		private bool VerifyEcDsa(IDigest digest, X9ECParameters curveParameter, byte[] buffer, int length, byte[] signature)
		{
			int digestSize = digest.GetDigestSize();

			ECDomainParameters dParams = new ECDomainParameters(
				curveParameter.Curve,
				curveParameter.G,
				curveParameter.N,
				curveParameter.H,
				curveParameter.GetSeed());

			ECPoint q = dParams.Curve.CreatePoint(new BigInteger(1, PublicKey, 0, digestSize), new BigInteger(1, PublicKey, digestSize, digestSize), false);

			ECPublicKeyParameters parameters = new ECPublicKeyParameters(q, dParams);

			var signer = new ECDsaSigner();
			signer.Init(false, parameters);

			digest.BlockUpdate(buffer, 0, length);
			byte[] hash = new byte[digest.GetDigestSize()];
			digest.DoFinal(hash, 0);

			return signer.VerifySignature(hash, new BigInteger(1, signature, 0, digestSize), new BigInteger(1, signature, digestSize, digestSize));
		}
Example #16
0
        public void TestECDsa239bitBinaryAndLargeDigest()
        {
            BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552");
            BigInteger s = new BigInteger("144940322424411242416373536877786566515839911620497068645600824084578597");

            byte[] kData = BigIntegers.AsUnsignedByteArray(
                new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363"));

            SecureRandom k = FixedSecureRandom.From(kData);

            F2mCurve curve = new F2mCurve(
                239, // m
                36, //k
                new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a
                new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(
                    Hex.Decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G
                new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n
                BigInteger.ValueOf(4)); // h

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d
                parameters);

            ECDsaSigner ecdsa = new ECDsaSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecdsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517968236873715988614170569073515315707566766479517968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecdsa.GenerateSignature(message);

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

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

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(
                    Hex.Decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Example #17
0
        public void TestECDsa239bitPrime()
        {
            BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176");
            BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783");

            byte[] kData = BigIntegers.AsUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655"));

            SecureRandom k = FixedSecureRandom.From(kData);

            FpCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

            ECDomainParameters parameters = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n

            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                "ECDSA",
                new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d
                parameters);

            ECDsaSigner ecdsa = new ECDsaSigner();
            ParametersWithRandom param = new ParametersWithRandom(priKey, k);

            ecdsa.Init(true, param);

            byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray();
            BigInteger[] sig = ecdsa.GenerateSignature(message);

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

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

            // Verify the signature
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
                "ECDSA",
                curve.DecodePoint(Hex.Decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q
                parameters);

            ecdsa.Init(false, pubKey);
            if (!ecdsa.VerifySignature(message, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Example #18
0
        public static bool VerifySignature(byte[] pubkey, byte[] hash, byte[] sigBytes)
        {
            X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters domainParameters = new ECDomainParameters(ecParams.Curve,
                ecParams.G, ecParams.N, ecParams.H,
                ecParams.GetSeed());

            BigInteger r = new BigInteger(1, sigBytes, 0, 32);
            BigInteger s = new BigInteger(1, sigBytes, 32, 32);
            ECPublicKeyParameters publicKey = new ECPublicKeyParameters(ecParams.Curve.DecodePoint(pubkey), domainParameters);

            ECDsaSigner signer = new ECDsaSigner();
            signer.Init(false, publicKey);
            return signer.VerifySignature(hash, r, s);
        }
Example #19
0
        public void TestECDsaP224Sha224()
        {
            X9ECParameters p = NistNamedCurves.GetByName("P-224");
            ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("6081831502424510080126737029209236539191290354021104541805484120491"), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("15456715103636396133226117016818339719732885723579037388121116732601")));

            byte[] M = Hex.Decode("8797A3C693CC292441039A4E6BAB7387F3B4F2A63D00ED384B378C79");

            ECDsaSigner dsa = new ECDsaSigner();

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

            BigInteger[] sig = dsa.GenerateSignature(M);

            BigInteger r = new BigInteger("26477406756127720855365980332052585411804331993436302005017227573742");
            BigInteger s = new BigInteger("17694958233103667059888193972742186995283044672015112738919822429978");

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

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

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

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(M, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        public byte[] Sign(byte[] data)
        {
            ECDsaSigner signer = new ECDsaSigner();
            ECDsaSigner signerverify = new ECDsaSigner();
            var ps = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
            ECDomainParameters ecParams = new ECDomainParameters(ps.Curve, ps.G, ps.N, ps.H);

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(m_Priv, ecParams);
            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(ecParams.Curve.DecodePoint(m_Pub), ecParams);

            signer.Init(true, privKey);
            signerverify.Init(false, pubKey);

            BigInteger[] sigs = signer.GenerateSignature(data);
            //sigs[0].BitLength sigs[1].BitLength

            bool bValid = signerverify.VerifySignature(data, sigs[0], sigs[1]);

            byte[] sig = new byte[64];
            for (int x = 0; x < 64; x++) sig[x] = 0;
            byte[] sig1 = sigs[0].ToByteArrayUnsigned();
            byte[] sig2 = sigs[1].ToByteArrayUnsigned();
            Array.Copy(sig1,0, sig,  0 + (32 - sig1.Length), sig1.Length);
            Array.Copy(sig2,0, sig, 32 + (32 - sig2.Length), sig2.Length);
            return sig;

            /*
                MemoryStream ms = new MemoryStream();
                DerSequenceGenerator seq = new DerSequenceGenerator(ms);
                seq.AddObject(new DerInteger(sigs[0]));
                seq.AddObject(new DerInteger(sigs[1]));
                seq.Close();
                return ms.ToArray();
             */
        }
Example #21
0
        public void TestECDsaP521Sha512()
        {
            X9ECParameters p = NistNamedCurves.GetByName("P-521");
            ECDomainParameters parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
                new BigInteger("617573726813476282316253885608633222275541026607493641741273231656161177732180358888434629562647985511298272498852936680947729040673640492310550142822667389"), // d
                parameters);
            SecureRandom k = FixedSecureRandom.From(BigIntegers.AsUnsignedByteArray(new BigInteger("6806532878215503520845109818432174847616958675335397773700324097584974639728725689481598054743894544060040710846048585856076812050552869216017728862957612913")));

            byte[] M = Hex.Decode("6893B64BD3A9615C39C3E62DDD269C2BAAF1D85915526083183CE14C2E883B48B193607C1ED871852C9DF9C3147B574DC1526C55DE1FE263A676346A20028A66");

            ECDsaSigner dsa = new ECDsaSigner();

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

            BigInteger[] sig = dsa.GenerateSignature(M);

            BigInteger r = new BigInteger("1368926195812127407956140744722257403535864168182534321188553460365652865686040549247096155740756318290773648848859639978618869784291633651685766829574104630");
            BigInteger s = new BigInteger("1624754720348883715608122151214003032398685415003935734485445999065609979304811509538477657407457976246218976767156629169821116579317401249024208611945405790");

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

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

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

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(M, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
        public void TestECDsaP256Sha256WithGeneratedKey()
        {
            var secureRandom = new SecureRandom();
            X9ECParameters p = NistNamedCurves.GetByName("P-256");
            var parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
            var ecParams = new ECKeyGenerationParameters(parameters, secureRandom);
            var ecGen = new ECKeyPairGenerator("ECDSA");
            ecGen.Init(ecParams);
            var pairKey = ecGen.GenerateKeyPair();
            var priKey = pairKey.Private as ECPrivateKeyParameters;

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

            var dsa = new ECDsaSigner();

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

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

            // Verify the signature
            var pubKey = pairKey.Public as ECPublicKeyParameters;

            dsa.Init(false, pubKey);
            if (!dsa.VerifySignature(m, sig[0], sig[1]))
            {
                Fail("signature fails");
            }
        }
Example #23
0
 /// <summary>
 /// Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
 /// </summary>
 /// <param name="data">Hash of the data to verify.</param>
 /// <param name="signature">ASN.1 encoded signature.</param>
 /// <param name="pub">The public key bytes to use.</param>
 public static bool Verify(byte[] data, byte[] signature, byte[] pub)
 {
     var signer = new ECDsaSigner();
     var @params = new ECPublicKeyParameters(_ecParams.Curve.DecodePoint(pub), _ecParams);
     signer.Init(false, @params);
     DerInteger r;
     DerInteger s;
     using (var decoder = new Asn1InputStream(signature))
     {
         var seq = (DerSequence) decoder.ReadObject();
         r = (DerInteger) seq[0];
         s = (DerInteger) seq[1];
     }
     return signer.VerifySignature(data, r.Value, s.Value);
 }
Example #24
0
        public bool VerifySignature(ImmutableArray<byte> scriptPubKey, Transaction tx, byte[] sig, byte[] pubKey, int inputIndex, out byte hashType, out byte[] txSignature, out byte[] txSignatureHash, out BigIntegerBouncy x, out BigIntegerBouncy y, out BigIntegerBouncy r, out BigIntegerBouncy s)
        {
            // get the 1-byte hashType off the end of sig
            hashType = sig[sig.Length - 1];

            // get the DER encoded portion of sig, which is everything except the last byte (the last byte being hashType)
            var sigDER = sig.Take(sig.Length - 1).ToArray();

            // get the simplified/signing version of the transaction
            txSignature = TxSignature(scriptPubKey, tx, inputIndex, hashType);

            // get the hash of the simplified/signing version of the transaction
            txSignatureHash = Crypto.DoubleSHA256(txSignature);

            // load pubKey
            ReadPubKey(pubKey, out x, out y);
            var publicKeyPoint = curve.Curve.CreatePoint(x, y, withCompression: false);
            var publicKeyParameters = new ECPublicKeyParameters(publicKeyPoint, domainParameters);

            // load sig
            ReadSigKey(sigDER, out r, out s);

            // init signer
            var signer = new ECDsaSigner();
            signer.Init(forSigning: false, parameters: publicKeyParameters);

            // verify that sig is a valid signature from pubKey for the simplified/signing transaction's hash
            var txSignatureHash2 = txSignatureHash;
            var r2 = r;
            var s2 = s;
            //TODO
            var result = BypassVerifySignature || new MethodTimer(false).Time("ECDsa Verify", () => signer.VerifySignature(txSignatureHash2.ToArray(), r2, s2));

            return result;
        }