public GenerateSignature ( byte message ) : Org.BouncyCastle.Math.BigInteger[] | ||
message | byte | |
리턴 | Org.BouncyCastle.Math.BigInteger[] |
/// <summary> /// Creates a signature for the given messsage and the given private key. /// </summary> /// <param name="message">The message.</param> /// <param name="privateKey">The array of 32 bytes of the private key.</param> /// <param name="useCompressedPublicKey">true to specify that the public key should have the compressed format; otherwise, false.</param> /// <exception cref="ArgumentException">The message is null or private key is null or invalid.</exception> /// <returns>The signature for the given message and the given private key in base-64 encoding.</returns> public static string SingMesssage(string message, byte[] privateKey, bool useCompressedPublicKey) { if (message == null) { throw new ArgumentException("The message is null.", nameof(message)); } if (privateKey == null) { throw new ArgumentException("The private key is null.", nameof(privateKey)); } if (!BitcoinPrivateKey.IsValid(privateKey)) { throw new ArgumentException("The private key is invalid.", nameof(privateKey)); } ECPrivateKeyParameters parameters = new ECPrivateKeyParameters(new BigInteger(1, privateKey), domainParameters); ECDsaSigner signer = new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest())); signer.Init(true, parameters); var hash = GetMessageHash(message); BigInteger[] signatureArray = signer.GenerateSignature(hash); BigInteger r = signatureArray[0]; BigInteger s = signatureArray[1]; s = NormalizeS(s); byte[] encodedPublicKey = BitcoinPrivateKey.ToEncodedPublicKey(privateKey, useCompressedPublicKey); int pubKeyMaskOffset = useCompressedPublicKey ? 4 : 0; Signature signature = null; for (int i = 0; i < 4; i++) { Signature candidateSignature = new Signature(); candidateSignature.PublicKeyMask = i + pubKeyMaskOffset; candidateSignature.R = r; candidateSignature.S = s; byte[] recoveredPublicKey = RecoverPublicKeyFromSignature(hash, candidateSignature); if (recoveredPublicKey != null && recoveredPublicKey.SequenceEqual(encodedPublicKey)) { signature = candidateSignature; break; } } if (signature == null) { // this should not happen throw new Exception("The public key is not recoverable from signature."); } return EncodeSignature(signature); }
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"); } }
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 Byte[] signData(Byte[] data) { if (privKey == null) throw new InvalidOperationException(); ECDsaSigner signer = new ECDsaSigner(); signer.Init(true, new ECPrivateKeyParameters(new BigInteger(1, privKey), ecParams)); BigInteger[] sig = signer.GenerateSignature(data); using (MemoryStream ms = new MemoryStream()) using (Asn1OutputStream asn1stream = new Asn1OutputStream(ms)) { DerSequenceGenerator seq = new DerSequenceGenerator(asn1stream); seq.AddObject(new DerInteger(sig[0])); seq.AddObject(new DerInteger(sig[1])); seq.Close(); return ms.ToArray(); } }
public static byte[] DoSignEcDsa( IEnumerable <BufLen> bufs, I2PSigningPrivateKey key, IDigest digest, X9ECParameters ecparam, int sigsize) { foreach (var buf in bufs) { digest.BlockUpdate(buf.BaseArray, buf.BaseArrayOffset, buf.Length); } var hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); var param = new ECDomainParameters(ecparam.Curve, ecparam.G, ecparam.N, ecparam.H); var pk = new ECPrivateKeyParameters(key.ToBigInteger(), param); var s = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner(); s.Init(true, new ParametersWithRandom(pk)); var sig = s.GenerateSignature(hash); var result = new byte[sigsize]; var b1 = sig[0].ToByteArrayUnsigned(); var b2 = sig[1].ToByteArrayUnsigned(); // https://geti2p.net/en/docs/spec/common-structures#type_Signature // When a signature is composed of two elements (for example values R,S), // it is serialized by padding each element to length/2 with leading zeros if necessary. // All types are Big Endian, except for EdDSA, which is stored and transmitted in a Little Endian format. // Pad msb. Big endian. Array.Copy(b1, 0, result, sigsize / 2 - b1.Length, b1.Length); Array.Copy(b2, 0, result, sigsize - b2.Length, b2.Length); DebugUtils.LogDebug("DoSignEcDsa: " + digest.ToString() + ": Used."); return(result); }
public static byte[] DoSignEcDsaSha256P256_old(IEnumerable <BufLen> bufs, I2PSigningPrivateKey key) { var sha = new Sha256Digest(); foreach (var buf in bufs) { sha.BlockUpdate(buf.BaseArray, buf.BaseArrayOffset, buf.Length); } var hash = new byte[sha.GetDigestSize()]; sha.DoFinal(hash, 0); var p = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByName("P-256"); var param = new ECDomainParameters(p.Curve, p.G, p.N, p.H); var pk = new ECPrivateKeyParameters(key.ToBigInteger(), param); var s = new Org.BouncyCastle.Crypto.Signers.ECDsaSigner(); s.Init(true, new ParametersWithRandom(pk)); var sig = s.GenerateSignature(hash); var result = new byte[64]; var b1 = sig[0].ToByteArrayUnsigned(); var b2 = sig[1].ToByteArrayUnsigned(); // https://geti2p.net/en/docs/spec/common-structures#type_Signature // When a signature is composed of two elements (for example values R,S), // it is serialized by padding each element to length/2 with leading zeros if necessary. // All types are Big Endian, except for EdDSA, which is stored and transmitted in a Little Endian format. // Pad msb. Big endian. Array.Copy(b1, 0, result, 0 + 20 - b1.Length, b1.Length); Array.Copy(b2, 0, result, 20 + 20 - b2.Length, b2.Length); DebugUtils.LogDebug("DoSignEcDsaSha256P256: Used."); return(result); }
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 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"); } }
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 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 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"); } }
public BigInteger[] Sign(byte[] message) { var q = new ECDsaSigner(); q.Init(true, this.keyPair.Private); var signature = q.GenerateSignature(message); return signature; }
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; }
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"); } }
public byte[] CreatePrivateKeyScript(Transaction tx, int inputIndex, byte hashType, ECPrivateKeyParameters privateKey, ECPublicKeyParameters publicKey) { //TODO var scriptEngine = new ScriptEngine(); var publicAddress = CreatePublicAddress(publicKey); var publicKeyScript = CreatePublicKeyScript(publicAddress); var txSignature = scriptEngine.TxSignature(publicKeyScript, tx, inputIndex, hashType); var txSignatureHash = SHA256Static.ComputeDoubleHash(txSignature); //Debug.WriteLine("Signing Tx: {0}".Format2(txSignature.ToHexDataString())); //Debug.WriteLine("Signing Tx Hash: {0}".Format2(txSignatureHash.ToHexDataString())); var signer = new ECDsaSigner(); signer.Init(forSigning: true, parameters: privateKey); var signature = signer.GenerateSignature(txSignatureHash); var r = signature[0]; var s = signature[1]; byte[] sigEncoded; using (var stream = new MemoryStream()) { using (var asn1Stream = new Asn1OutputStream(stream)) { asn1Stream.WriteObject(new DerSequence(new DerInteger(r), new DerInteger(s))); } sigEncoded = stream.ToArray().Concat(hashType); } //Debug.WriteLine("Sig R: {0}".Format2(r.ToHexNumberStringUnsigned())); //Debug.WriteLine("Sig S: {0}".Format2(s.ToHexNumberStringUnsigned())); //Debug.WriteLine("Sig Encoded: {0}".Format2(sigEncoded.ToHexDataString())); using (var privateKeyScript = new ScriptBuilder()) { privateKeyScript.WritePushData(sigEncoded); privateKeyScript.WritePushData(publicAddress); //Debug.WriteLine("Private Script: {0}".Format2(privateKeyScript.GetScript().ToHexDataString())); return privateKeyScript.GetScript(); } }
private static EcdsaSignature CreateEcdsaSignature(byte[] bytes, BigInteger secret) { var signer = new ECDsaSigner(); var privKey = new ECPrivateKeyParameters(secret, Secp256K1.Params()); signer.Init(true, privKey); BigInteger[] sigs = signer.GenerateSignature(bytes); BigInteger r = sigs[0], s = sigs[1]; BigInteger otherS = Secp256K1.Order().Subtract(s); if (s.CompareTo(otherS) == 1) { s = otherS; } return new EcdsaSignature(r, s); }
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(); */ }
public static void FullSignatureTest(byte[] hash) { X9ECParameters ecParams = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1"); ECDomainParameters 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(); ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.Private; ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.Public; Console.WriteLine("Generated private key: " + ToHex(privateKey.D.ToByteArrayUnsigned())); Console.WriteLine("Generated public key: " + ToHex(publicKey.Q.GetEncoded())); ECDsaSigner signer = new ECDsaSigner(); signer.Init(true, privateKey); BigInteger[] sig = signer.GenerateSignature(hash); int recid = -1; for (int rec=0; rec<4; rec++) { try { ECPoint Q = ECDSA_SIG_recover_key_GFp(sig, hash, rec, true); if (ToHex(publicKey.Q.GetEncoded()).Equals(ToHex(Q.GetEncoded()))) { recid = rec; break; } } catch (Exception) { continue; } } if (recid < 0) throw new Exception("Did not find proper recid"); byte[] fullSigBytes = new byte[65]; fullSigBytes[0] = (byte) (27+recid); Buffer.BlockCopy(sig[0].ToByteArrayUnsigned(), 0, fullSigBytes, 1, 32); Buffer.BlockCopy(sig[1].ToByteArrayUnsigned(), 0, fullSigBytes, 33, 32); Console.WriteLine("Generated full signature: " + Convert.ToBase64String(fullSigBytes)); byte[] sigBytes = new byte[64]; Buffer.BlockCopy(sig[0].ToByteArrayUnsigned(), 0, sigBytes, 0, 32); Buffer.BlockCopy(sig[1].ToByteArrayUnsigned(), 0, sigBytes, 32, 32); ECPoint genQ = ECDSA_SIG_recover_key_GFp(sig, hash, recid, false); Console.WriteLine("Generated signature verifies: " + VerifySignature(genQ.GetEncoded(), hash, sigBytes)); }
public void Sign(AsymmetricKeyParameter privateKey) { var signer = new ECDsaSigner(); signer.Init(true, privateKey); var signature = signer.GenerateSignature(t.getBytes); r = signature[0].ToByteArray(); s = signature[1].ToByteArray(); }
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"); } }
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"); } }
/// <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) { var signer = new ECDsaSigner(); var privKey = new ECPrivateKeyParameters(_priv, _ecParams); signer.Init(true, privKey); var sigs = 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 bos = new MemoryStream()) { var seq = new DerSequenceGenerator(bos); seq.AddObject(new DerInteger(sigs[0])); seq.AddObject(new DerInteger(sigs[1])); seq.Close(); return bos.ToArray(); } }
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"); } }
private byte[] SignEcDsa(IDigest digest, byte[] buffer, int length) { int digestSize = digest.GetDigestSize(); ECDsaSigner signer = new ECDsaSigner(); signer.Init(true, new ParametersWithRandom(PrivateKeyFactory.CreateKey(PrivateKey), _secureRandom)); digest.BlockUpdate(buffer, 0, length); byte[] hash = new byte[digest.GetDigestSize()]; digest.DoFinal(hash, 0); var signature = signer.GenerateSignature(hash); byte[] res = new byte[digestSize * 2]; signature[0].ToByteArrayUnsigned().CopyTo(res, 0); signature[1].ToByteArrayUnsigned().CopyTo(res, digestSize); return res; }
public ECDSASignature Sign(uint256 hash) { AssertPrivateKey(); ECDsaSigner signer = new ECDsaSigner(); signer.Init(true, PrivateKey); BigInteger[] components = signer.GenerateSignature(hash.ToBytes()); ECDSASignature signature = new ECDSASignature(components[0], components[1]); signature = signature.MakeCanonical(); return signature; }