public void OpCheckSig(ParsedOpCode op, MsgTx transaction) { try { var rawPublicKey = MainStack.Pop(); var rawSignature = MainStack.Pop(); if (rawSignature.Length < 1) { MainStack.Push(false); return; } var signature = rawSignature.Take(rawSignature.Length - 1).ToArray(); var signatureType = (SignatureHashType)rawSignature.Last(); AssertSignatureHashType(signatureType); AssertSignatureEncoding(signature); AssertPublicKeyEncoding(rawPublicKey); var subScript = _script.GetOpCodesWithoutData(rawSignature); var hash = CalculateSignatureHash(subScript, signatureType, (MsgTx)transaction.Clone(), _txIndex); var ecSignature = new ECSignature(signature); var securityService = new ECPublicSecurityService(rawPublicKey); var isValidSignature = securityService.VerifySignature(hash, ecSignature); MainStack.Push(isValidSignature); } catch (ScriptException) { MainStack.Push(false); } }
public override void LoadFromStream(Stream s) { using (BinaryReader br = new BinaryReader(s, Encoding.Default, true)) { SignerAccount = br.ReadUInt32(); switch (TransactionType) { case TransactionType.ChangeKey: TargetAccount = SignerAccount; break; case TransactionType.ChangeKeySigned: TargetAccount = br.ReadUInt32(); break; } NumberOfOperations = br.ReadUInt32(); Fee = br.ReadUInt64(); Payload = ByteString.ReadFromStream(br); AccountKey = new ECKeyPair(); AccountKey.LoadFromStream(s, false); NewAccountKey = new ECKeyPair(); NewAccountKey.LoadFromStream(s); Signature = new ECSignature(s); } }
public async Task <JObject> SignHash(string address, string password, string hash) { var tryOpen = KeyStore.OpenAsync(address, password); if (tryOpen == AElfKeyStore.Errors.WrongPassword) { return(new JObject() { ["error"] = "Wrong password." }); } ECKeyPair kp = KeyStore.GetAccountKeyPair(address); byte[] toSig = ByteArrayHelpers.FromHexString(hash); // Sign the hash ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(kp, toSig); // TODO: Standardize encoding return(new JObject() { ["R"] = signature.R, ["S"] = signature.S, ["P"] = kp.PublicKey.Q.GetEncoded() }); }
public void SignAndVerifyTransaction() { // Generate the key pair ECKeyPair keyPair = new KeyPairGenerator().Generate(); Transaction tx = new Transaction(); tx.From = Address.FromRawBytes(CryptoHelpers.RandomFill(ADR_LENGTH)); tx.To = Address.FromRawBytes(CryptoHelpers.RandomFill(ADR_LENGTH)); Block block = new Block(); block.AddTransaction(tx); // Serialize and hash the transaction Hash hash = tx.GetHash(); // Sign the hash ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(keyPair, hash.DumpByteArray()); ECVerifier verifier = new ECVerifier(keyPair); Assert.True(verifier.Verify(signature, hash.DumpByteArray())); }
/*public Transaction SignTransaction(JObject t) * { * Transaction tr = new Transaction(); * * try * { * tr.From = ByteArrayHelpers.FromHexString(addr); * tr.To = Convert.FromBase64String(t["to"].ToString()); * tr.IncrementId = t["incr"].ToObject<ulong>(); * tr.MethodName = t["method"].ToObject<string>(); * var p = Convert.FromBase64String(t["params"].ToString()); * tr.Params = p.Length == 0 ? null : p; * * SignTransaction(tr); * * return tr; * } * catch (Exception e) * { * ; * } * * return null; * }*/ public Transaction SignTransaction(Transaction tx) { string addr = tx.From.Value.ToHex(true); ECKeyPair kp = _keyStore.GetAccountKeyPair(addr); if (kp == null) { throw new AccountLockedException(addr); } MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, tx); byte[] b = ms.ToArray(); byte[] toSig = SHA256.Create().ComputeHash(b); // Sign the hash ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(kp, toSig); // Update the signature tx.Sig = new Signature { R = signature.R, S = signature.S, P = kp.PublicKey.Q.GetEncoded() }; return(tx); }
public static Transaction BuildTransaction(Address adrTo = null, ulong nonce = 0, ECKeyPair keyPair = null) { keyPair = keyPair ?? new KeyPairGenerator().Generate(); var tx = new Transaction(); tx.From = keyPair.GetAddress(); tx.To = adrTo ?? Address.FromRawBytes(Hash.Generate().ToByteArray()); tx.IncrementId = nonce; tx.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()) }; tx.Fee = TxPoolConfig.Default.FeeThreshold + 1; tx.MethodName = "hello world"; tx.Params = ByteString.CopyFrom(new Parameters { Params = { new Param { IntVal = 1 } } }.ToByteArray()); // Serialize and hash the transaction Hash hash = tx.GetHash(); // Sign the hash ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(keyPair, hash.DumpByteArray()); // Update the signature tx.Sig.R = ByteString.CopyFrom(signature.R); tx.Sig.S = ByteString.CopyFrom(signature.S); return(tx); }
public Transaction SignTransaction(Transaction tx) { string addr = tx.From.Value.ToHex(); ECKeyPair kp = _keyStore.GetAccountKeyPair(addr); if (kp == null) { Console.WriteLine("The following account is locked:" + addr); return(null); } MemoryStream ms = new MemoryStream(); Serializer.Serialize(ms, tx); byte[] b = ms.ToArray(); byte[] toSig = SHA256.Create().ComputeHash(b); // Sign the hash ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(kp, toSig); // Update the signature tx.R = signature.R; tx.S = signature.S; tx.P = kp.PublicKey.Q.GetEncoded(); return(tx); }
/// <summary> /// This method sends authentification information to the distant peer and /// start the authentification timer. /// </summary> /// <returns></returns> private void StartAuthentification() { var nodeInfo = new NodeData { Port = _port }; ECSigner signer = new ECSigner(); ECSignature sig = signer.Sign(_nodeKey, nodeInfo.ToByteArray()); var nd = new Handshake { NodeInfo = nodeInfo, PublicKey = ByteString.CopyFrom(_nodeKey.GetEncodedPublicKey()), Height = CurrentHeight, Version = GlobalConfig.ProtocolVersion, R = ByteString.CopyFrom(sig.R), S = ByteString.CopyFrom(sig.S) }; byte[] packet = nd.ToByteArray(); _logger?.Trace($"Sending authentification : {{ port: {nd.NodeInfo.Port}, addr: {nd.PublicKey.ToByteArray().ToHex()} }}"); _messageWriter.EnqueueMessage(new Message { Type = (int)MessageType.Auth, HasId = false, Length = packet.Length, Payload = packet }); StartAuthTimer(); }
/// <summary> /// initialise updater. /// </summary> /// <param name="updateDir"></param> public UpdateController(string updateDir, TroubleShooterClient client) { this._client = client; _updateDir = updateDir; ElipticCurve curve = ElipticCurve.secp160r1(); _keyGen = new ECKeysGenerator(curve); _verifier = new ECSignature(curve); _diffieHelman = new ECDiffieHelman(curve); }
/// <summary> /// <see cref="TroubleshooterController"/> /// </summary> public TroubleshooterController(ServisContext ctx) { this.ctx = ctx; ElipticCurve curve = ElipticCurve.secp160r1(); signatureMaker = new ECSignature(curve); keyGen = new ECKeysGenerator(curve); diffieHelman = new ECDiffieHelman(curve); sourceFiles = SourceFileInfoBuilder.GetSourceFiles(SOURCE_FILES_DIR); rnd = new Random(); }
/// <summary> /// block signature /// </summary> /// <param name="keyPair"></param> /// <exception cref="NotImplementedException"></exception> public void Sign(ECKeyPair keyPair) { ECSigner signer = new ECSigner(); var hash = GetHash(); var bytes = hash.DumpByteArray(); ECSignature signature = signer.Sign(keyPair, bytes); Header.P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()); Header.R = ByteString.CopyFrom(signature.R); Header.S = ByteString.CopyFrom(signature.S); }
public virtual bool VerifyECSignature(ECPublicKey publicKey, ECSignature signature, byte[] data) { var curve = ECNamedCurveTable.GetByName(CURVEALGO); var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed()); ECDsaSigner verifier = new ECDsaSigner(); verifier.Init(false, new ECPublicKeyParameters(domainParams.Curve.DecodePoint(publicKey.Base64Array), domainParams)); return(verifier.VerifySignature(data, signature.GetR(), signature.GetS())); }
public void VerifySignature_CorrectDataAndSig_ReturnsTrue() { ECKeyPair keyPair = new KeyPairGenerator().Generate(); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(keyPair, message); ECVerifier verifier = new ECVerifier(keyPair); Assert.True(verifier.Verify(signature, message)); }
public void ECSecurityService_VerifySignature_VerifiesGeneratedSignatureAgainstPublicKey() { const bool isCompressed = false; var messageHash = HashUtil.Blake256(_message); var signature = new ECSignature(_signature); var privateSecurityService = new ECPrivateSecurityService(_privateKey); var publicKeyBytes = privateSecurityService.GetPublicKey(isCompressed); var publicSecurityService = new ECPublicSecurityService(publicKeyBytes); var hasValidSignature = publicSecurityService.VerifySignature(messageHash, signature); Assert.True(hasValidSignature); }
public void VerifySignatureTest() { var curve = ECCurve.Secp256k1; var publicKey = curve.CreatePublicKey("0474938fcc21b40cd1fcb3e98df92c4239af59ef46f404a7d15ed659dcbdcda1326a7cd3040a023919418014d1b2c96b3b32467787938e82994b050d9968a8c5d2"); var msg = BigIntegerExt.ParseHexUnsigned("7846e3be8abd2e089ed812475be9b51c3cfcc1a04fafa2ddb6ca6869bf272715"); var random = BigIntegerExt.ParseHexUnsigned("cd6f06360fa5af8415f7a678ab45d8c1d435f8cf054b0f5902237e8cb9ee5fe5"); var signature = new ECSignature( BigIntegerExt.ParseHexUnsigned("2794dd08b1dfa958552bc37916515a3accb0527e40f9291d62cc4316047d24dd"), BigIntegerExt.ParseHexUnsigned("5dd1f95f962bb6871967dc17b22217100daa00a3756feb1e16be3e6936fd8594"), curve ); var result = publicKey.VerifySignature(msg, signature); Assert.IsTrue(result); }
public void TestSignature(ElipticCurve curve, int iterations) { ECKeysGenerator keyGen = new ECKeysGenerator(curve); ECSignature signature = new ECSignature(curve); for (int i = 0; i < iterations; i++) { Console.WriteLine($"signature curve {curve.Name} test {i}... "); //generovanie klucoveho paru byte[] privateKey1; byte[] publicKey1; keyGen.GenerateKeyPair(out privateKey1, out publicKey1); byte[] privateKey2; byte[] publicKey2; keyGen.GenerateKeyPair(out privateKey2, out publicKey2); string str1 = RandomString(random.Next(100)); string str2 = RandomString(random.Next(100)); while (str1 == str2) { str2 = RandomString(random.Next(100)); } byte[] sign1 = signature.Signature(str1, privateKey1); byte[] sign2 = signature.Signature(str2, privateKey1); Console.WriteLine(Convert.ToBase64String(sign1)); if (!signature.VerifySignature(str1, sign1, publicKey1)) { Write($"Signature should be valid !!! ", ConsoleColor.Red); throw new Exception("Fatal error"); } if (signature.VerifySignature(str1, sign1, publicKey2)) { Write($"Signature should not be valid because of wrong public key !!!", ConsoleColor.DarkYellow); } if (signature.VerifySignature(str2, sign1, publicKey1)) { Console.WriteLine(); Write($"Signature should not be valid because of changed message!!!", ConsoleColor.DarkYellow); } else { Write("OK", ConsoleColor.Green); } } }
public List <Transaction> CreateTx(Hash chainId) { var contractAddressZero = AddressHelpers.GetSystemContractAddress(chainId, GlobalConfig.GenesisBasicContract); Console.WriteLine($"zero {contractAddressZero}"); var code = ExampleContractCode; ECKeyPair keyPair = new KeyPairGenerator().Generate(); ECSigner signer = new ECSigner(); var txPrint = new Transaction() { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = NewIncrementId(), MethodName = "Print", Params = ByteString.CopyFrom(new Parameters() { Params = { new Param { StrVal = "AElf" } } }.ToByteArray()), Fee = TxPoolConfig.Default.FeeThreshold + 1 }; Hash hash = txPrint.GetHash(); ECSignature signature = signer.Sign(keyPair, hash.DumpByteArray()); txPrint.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature.R), S = ByteString.CopyFrom(signature.S), }; var txs = new List <Transaction>() { txPrint }; return(txs); }
public void SignAndVerifyTransaction() { byte[] fromAdress = CryptoHelpers.RandomFill(ADR_LENGTH); byte[] toAdress = CryptoHelpers.RandomFill(ADR_LENGTH); // Generate the key pair ECKeyPair keyPair = new KeyPairGenerator().Generate(); ; Transaction tx = new Transaction(); tx.From = Address.FromRawBytes(fromAdress); tx.To = Address.FromRawBytes(toAdress); tx.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()) }; // Serialize and hash the transaction Hash hash = tx.GetHash(); // Sign the hash ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(keyPair, hash.DumpByteArray()); // Update the signature tx.Sig.R = ByteString.CopyFrom(signature.R); tx.Sig.S = ByteString.CopyFrom(signature.S); // Serialize as for sending over the network byte[] serializedTx = tx.Serialize(); /**** broadcast/receive *****/ Transaction dTx = Transaction.Parser.ParseFrom(serializedTx); // Serialize and hash the transaction Hash dHash = dTx.GetHash(); byte[] uncompressedPrivKey = tx.Sig.P.ToByteArray(); ECKeyPair recipientKeyPair = ECKeyPair.FromPublicKey(uncompressedPrivKey); ECVerifier verifier = new ECVerifier(recipientKeyPair); Assert.True(verifier.Verify(dTx.GetSignature(), dHash.DumpByteArray())); }
public void VerifySignature_WrongData_ReturnsFalse() { ECKeyPair keyPair = new KeyPairGenerator().Generate(); byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(keyPair, message); // Change the message message = new BigInteger("9682368737159881417056907351531570756676647951").ToByteArray(); ECVerifier verifier = new ECVerifier(keyPair); Assert.False(verifier.Verify(signature, message)); }
static void Main(string[] args) { ECKeyPair keyPair = KeyPairGenerator.Generate(); //Console.WriteLine(privateKey.ToString() + Environment.NewLine); // Fake data byte[] message = new BigInteger("968236873715988614170569073515315707566766479517").ToByteArray(); ECSigner signer = new ECSigner(); ECSignature signature = signer.Sign(keyPair, message); message = new BigInteger("9682368737159881417056907351531570756676647951").ToByteArray(); ECVerifier verifier = new ECVerifier(keyPair); bool isGood = verifier.Verify(signature, message); Console.WriteLine(isGood); }
public override void LoadFromStream(Stream stream) { using (BinaryReader br = new BinaryReader(stream, Encoding.Default, true)) { SignerAccount = br.ReadUInt32(); TargetAccount = br.ReadUInt32(); NumberOfOperations = br.ReadUInt32(); Fee = br.ReadUInt64(); Payload = ByteString.ReadFromStream(br); AccountKey = new ECKeyPair(); AccountKey.LoadFromStream(stream, false); ChangeType = br.ReadByte(); NewAccountKey = new ECKeyPair(); NewAccountKey.LoadFromStream(stream, false); NewName = ByteString.ReadFromStream(br); NewType = br.ReadUInt16(); Signature = new ECSignature(stream); } }
public static (ECKeyPair, Handshake) CreateKeyPairAndHandshake(int port) { ECKeyPair key = new KeyPairGenerator().Generate(); var nodeInfo = new NodeData { Port = port }; ECSigner signer = new ECSigner(); ECSignature sig = signer.Sign(key, nodeInfo.ToByteArray()); var handshakeMsg = new Handshake { NodeInfo = nodeInfo, PublicKey = ByteString.CopyFrom(key.GetEncodedPublicKey()), R = ByteString.CopyFrom(sig.R), S = ByteString.CopyFrom(sig.S), }; return(key, handshakeMsg); }
public override void LoadFromStream(Stream stream) { using (BinaryReader br = new BinaryReader(stream, Encoding.ASCII, true)) { SignerAccount = br.ReadUInt32(); NumberOfOperations = br.ReadUInt32(); TargetAccount = br.ReadUInt32(); Amount = br.ReadUInt64(); Fee = br.ReadUInt64(); Payload = ByteString.ReadFromStream(br); AccountKey = new ECKeyPair(); AccountKey.LoadFromStream(stream, false); //stream.Position -= 1; byte b = br.ReadByte(); TransactionStyle = (TransferType)b; if (b > 2) { stream.Position -= 1; TransactionStyle = TransferType.Transaction; TransactionType = TransactionType.Transaction; } if (b > 0 && b < 3) { AccountPrice = br.ReadUInt64(); SellerAccount = br.ReadUInt32(); NewAccountKey = new ECKeyPair(); NewAccountKey.LoadFromStream(stream, false); switch (TransactionStyle) { case TransferType.BuyAccount: TransactionType = TransactionType.BuyAccount; break; case TransferType.TransactionAndBuyAccount: TransactionType = TransactionType.BuyAccount; break; default: TransactionType = TransactionType.Transaction; break; } } Signature = new ECSignature(stream); } }
public override void LoadFromStream(Stream s) { using (BinaryReader br = new BinaryReader(s, Encoding.Default, true)) { SignerAccount = br.ReadUInt32(); TargetAccount = br.ReadUInt32(); TransactionType = (TransactionType)br.ReadUInt16(); NumberOfOperations = br.ReadUInt32(); if (TransactionType == TransactionType.ListAccountForSale) { AccountPrice = br.ReadUInt64(); AccountToPay = br.ReadUInt32(); AccountKey = new ECKeyPair(); AccountKey.LoadFromStream(s, false); NewPublicKey = new ECKeyPair(); NewPublicKey.LoadFromStream(s); LockedUntilBlock = br.ReadUInt32(); } Fee = br.ReadUInt64(); Payload = ByteString.ReadFromStream(br); Signature = new ECSignature(s); } }
public List <Transaction> CreateTxs(Hash chainId) { var contractAddressZero = AddressHelpers.GetSystemContractAddress(chainId, GlobalConfig.GenesisBasicContract); var code = ExampleContractCode; ECKeyPair keyPair = new KeyPairGenerator().Generate(); ECSigner signer = new ECSigner(); var txnDep = new Transaction() { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = 0, MethodName = "DeploySmartContract", Params = ByteString.CopyFrom(ParamsPacker.Pack((int)0, code)), Fee = TxPoolConfig.Default.FeeThreshold + 1, Type = TransactionType.ContractTransaction }; Hash hash = txnDep.GetHash(); ECSignature signature1 = signer.Sign(keyPair, hash.DumpByteArray()); txnDep.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature1.R), S = ByteString.CopyFrom(signature1.S), }; var txInv_1 = new Transaction { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = 1, MethodName = "Print", Params = ByteString.CopyFrom(ParamsPacker.Pack("AElf")), Fee = TxPoolConfig.Default.FeeThreshold + 1, Type = TransactionType.ContractTransaction }; ECSignature signature2 = signer.Sign(keyPair, txInv_1.GetHash().DumpByteArray()); txInv_1.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()), R = ByteString.CopyFrom(signature2.R), S = ByteString.CopyFrom(signature2.S) }; var txInv_2 = new Transaction { From = keyPair.GetAddress(), To = contractAddressZero, IncrementId = txInv_1.IncrementId, MethodName = "Print", Params = ByteString.CopyFrom(ParamsPacker.Pack("AElf")), Fee = TxPoolConfig.Default.FeeThreshold + 1, Type = TransactionType.ContractTransaction }; ECSignature signature3 = signer.Sign(keyPair, txInv_2.GetHash().DumpByteArray()); txInv_2.Sig = new Signature { P = ByteString.CopyFrom(keyPair.PublicKey.Q.GetEncoded()) }; txInv_2.Sig.R = ByteString.CopyFrom(signature3.R); txInv_2.Sig.S = ByteString.CopyFrom(signature3.S); var txs = new List <Transaction>() { txnDep, txInv_1, txInv_2 }; return(txs); }
public bool VerifySignature(byte[] message, ECSignature signature) { return(_ecPublicSecurityService.VerifySignature(message, signature)); }