Beispiel #1
0
        //Sign transaction using private key
        public byte[] SignTx(Key priv)
        {
            //Get serialized transaction
            byte[] tx = this.Serialize();

            //Debugging
            Console.WriteLine("Serialized Tx: ");
            foreach (byte b in tx)
            {
                Console.Write((int)b + " ");
            }
            Console.WriteLine();

            //Generate ECDSA signature
            ECDsaSigner            signer     = new ECDsaSigner(new HMacDsaKCalculator(new Sha256Digest()));
            ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters(new BigInteger(1, priv.ToBytes()), domain);

            signer.Init(true, privateKey);
            BigInteger[] components = signer.GenerateSignature(this.Hash);

            //Debugging
            Console.WriteLine("Hash value: ");
            foreach (byte b in this.Hash)
            {
                Console.Write((int)b + " ");
            }
            Console.WriteLine();
            Console.WriteLine(components[0] + " " + components[1]);
            ECDSASignature ecdsaSignature = new ECDSASignature(components[0], components[1]).ToCanonicalised();

            //Encode to DER
            byte[] sigs = ecdsaSignature.EncodeToDER();

            //Debugging
            Console.WriteLine("Signature: ");
            foreach (byte b in sigs)
            {
                Console.Write((int)b + " ");
            }
            Console.WriteLine();

            byte[] sigsLen   = BitConverter.GetBytes(sigs.Length);
            byte[] pubKey    = priv.PubKey.ToBytes();
            byte[] pubKeyLen = BitConverter.GetBytes(pubKey.Length);

            //Reverse to big endian
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(sigsLen);
                Array.Reverse(pubKeyLen);
            }

            //Format: sigLen + sigs + pubKeyLen + pubKey + serialized Tx
            List <byte> result = new List <byte>();

            result.AddRange(sigsLen);
            result.AddRange(sigs);
            result.AddRange(pubKeyLen);
            result.AddRange(pubKey);
            result.AddRange(tx);

            Console.WriteLine("Signed bytes: ");
            foreach (byte b in result)
            {
                Console.Write((int)b + " ");
            }
            Console.WriteLine();

            Console.WriteLine("Signed Transaction: " + Convert.ToBase64String(result.ToArray()));

            return(result.ToArray());
        }