Exemple #1
0
        static void Main(string[] args)
        {
            // Create a secp256k1 context (ensure disposal to prevent unmanaged memory leaks).
            using (var secp256k1 = new Secp256k1())
            {
                // Generate a private key.
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256k1.SecretKeyVerify(privateKey));


                // Create public key from private key.
                var publicKey = new byte[64];
                Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey));


                // Sign a message hash.
                var messageBytes = Encoding.UTF8.GetBytes("Hello world.");
                var messageHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes);
                var signature    = new byte[64];
                Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey));

                // Serialize a DER signature from ECDSA signature
                byte[] signatureDer = new byte[Secp256k1.SERIALIZED_DER_SIGNATURE_MAX_SIZE];
                int    outL         = 0;
                Debug.Assert(secp256k1.SignatureSerializeDer(signatureDer, signature, out outL));
                Array.Resize(ref signatureDer, outL);

                // Verify message hash.
                Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey));
            }
        }
Exemple #2
0
        /// <summary>
        /// Attachs the envelope.
        /// </summary>
        /// <param name="blindSum">Blind sum.</param>
        /// <param name="commitSum">Commit sum.</param>
        /// <param name="balance">Balance.</param>
        /// <param name="secret">Secret.</param>
        /// <param name="coin">Coin.</param>
        private void AttachEnvelope(byte[] blindSum, byte[] commitSum, ulong balance, SecureString secret, SecureString salt, ref CoinDto coin)
        {
            var(k1, k2) = Split(blindSum, secret, salt, coin.Stamp, coin.Version);

            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var bulletProof = new BulletProof())
                    {
                        coin.Envelope.Commitment = commitSum.ToHex();
                        coin.Envelope.Proof      = k2.ToHex();
                        coin.Envelope.PublicKey  = pedersen.ToPublicKey(pedersen.Commit(0, k1)).ToHex();
                        coin.Hash = Hash(coin).ToHex();
                        coin.Envelope.Signature = secp256k1.Sign(coin.Hash.FromHex(), k1).ToHex();

                        var @struct = bulletProof.ProofSingle(balance, blindSum, Cryptography.RandomBytes(), null, null, null);
                        var success = bulletProof.Verify(commitSum, @struct.proof, null);

                        if (!success)
                        {
                            throw new ArgumentOutOfRangeException(nameof(success), "Bullet proof failed.");
                        }

                        coin.Envelope.RangeProof = @struct.proof.ToHex();
                    }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            // Create a secp256k1 context (ensure disposal to prevent unmanaged memory leaks).
            using (var secp256k1 = new Secp256k1())
            {
                // Generate a private key.
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256k1.SecretKeyVerify(privateKey));


                // Create public key from private key.
                var publicKey = new byte[64];
                Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey));


                // Sign a message hash.
                var messageBytes = Encoding.UTF8.GetBytes("Hello world.");
                var messageHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes);
                var signature    = new byte[64];
                Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey));


                // Verify message hash.
                Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey));
            }
        }
        static void TestToPublicKey()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    var blinding  = secp256k1.CreatePrivateKey();
                    var commitPos = pedersen.Commit(0, blinding);
                    var commitNeg = pedersen.Commit(0, blinding);

                    var blindSum = pedersen.BlindSum(new List <byte[]> {
                        blinding, blinding
                    }, new List <byte[]> {
                    });

                    var commitSum = pedersen.CommitSum(new List <byte[]> {
                        commitPos
                    }, new List <byte[]> {
                        commitNeg
                    });

                    var msg      = "Message for signing";
                    var msgBytes = Encoding.UTF8.GetBytes(msg);
                    var msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                    var sig = secp256k1.Sign(msgHash, blinding);

                    var pubKey = pedersen.ToPublicKey(commitSum);

                    var verified1 = secp256k1.Verify(sig, msgHash, pubKey);
                    var pub       = secp256k1.CreatePublicKey(blinding);
                }
        }
 public static byte[] GenerateSignatureSecp256k1(byte[] privateKey, byte[] data)
 {
     lock (ecdsaLock)
     {
         return(secp256k1.Sign(privateKey, data));
     }
 }
Exemple #6
0
        public void Sign_With_PubKey_From_Commitment()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    string ToHex(byte[] data)
                    {
                        return(BitConverter.ToString(data).Replace("-", string.Empty));
                    }

                    var blinding = secp256k1.CreatePrivateKey();
                    var commit   = pedersen.Commit(0, blinding);

                    var msg      = "Message for signing";
                    var msgBytes = Encoding.UTF8.GetBytes(msg);
                    var msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                    var sig = secp256k1.Sign(msgHash, blinding);

                    var pubKey = pedersen.ToPublicKey(commit);

                    Assert.True(secp256k1.Verify(sig, msgHash, pubKey));

                    var actualPubKey = secp256k1.CreatePublicKey(blinding);

                    Assert.Equal(ToHex(pubKey), ToHex(actualPubKey));
                }
        }
Exemple #7
0
        /// <summary>
        /// Signs with blinding factor.
        /// </summary>
        /// <returns>The with blinding.</returns>
        /// <param name="msg">Message.</param>
        /// <param name="blinding">Blinding.</param>
        public byte[] SignWithBlinding(byte[] msg, byte[] blinding)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(msg));
            }

            if (blinding == null)
            {
                throw new ArgumentNullException(nameof(blinding));
            }

            if (blinding.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(blinding));
            }

            using (var secp256k1 = new Secp256k1())
            {
                var msgHash = Cryptography.GenericHashNoKey(Encoding.UTF8.GetString(msg));
                return(secp256k1.Sign(msgHash, blinding));
            }
        }
Exemple #8
0
        public byte[] Sign(HashDigest <T> messageHash, PrivateKey privateKey)
        {
            lock (_instanceLock)
            {
                var secp256K1Signature = new byte[Secp256k1.SIGNATURE_LENGTH];
                var privateKeyBytes    = new byte[Secp256k1.PRIVKEY_LENGTH];

                privateKey.ByteArray.CopyTo(
                    privateKeyBytes,
                    Secp256k1.PRIVKEY_LENGTH - privateKey.ByteArray.Length);

                _instance.Sign(
                    secp256K1Signature,
                    messageHash.ToByteArray(),
                    privateKeyBytes);

                var signature = new byte[Secp256k1.SERIALIZED_DER_SIGNATURE_MAX_SIZE];
                _instance.SignatureSerializeDer(
                    signature,
                    secp256K1Signature,
                    out int signatureLength);

                return(signature.Take(signatureLength).ToArray());
            }
        }
Exemple #9
0
        /// <summary>
        /// Sign the specified amount, version, stamp, password and msg.
        /// </summary>
        /// <returns>The sign.</returns>
        /// <param name="amount">Amount.</param>
        /// <param name="version">Version.</param>
        /// <param name="stamp">Stamp.</param>
        /// <param name="password">Password.</param>
        /// <param name="msg">Message.</param>
        public byte[] Sign(ulong amount, int version, string stamp, SecureString password, byte[] msg)
        {
            if (string.IsNullOrEmpty(stamp))
            {
                throw new ArgumentNullException(nameof(stamp));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(msg));
            }

            using (var secp256k1 = new Secp256k1())
            {
                var blind = DeriveKey(version, stamp, password).FromHex();
                var sig   = secp256k1.Sign(msg, blind);

                return(sig);
            }
        }
        public void SetupVerify()
        {
            SetupSign();

            Span <byte> sk = new byte[64];

            sk = privateKey;

            Span <byte> m = new byte[32];

            m = message;

            Span <byte> sig = new byte[64];

            secp256k1.Sign(sig, message, sk);
            signature = sig.ToArray();
        }
Exemple #11
0
        public static byte[] Sign(object data, byte[] privateKey)
        {
            var signature = new byte[64];
            var dataHash  = ObjectToSha256(data);

            using (var secp256k1 = new Secp256k1())
            {
                secp256k1.Sign(signature, dataHash, privateKey);
                return(signature);
            }
        }
Exemple #12
0
        /// <summary>
        /// Signs with blinding factor.
        /// </summary>
        /// <returns>The with blinding.</returns>
        /// <param name="msg">Message.</param>
        /// <param name="blinding">Blinding.</param>
        public byte[] SignWithBlinding(byte[] msg, byte[] blinding)
        {
            Guard.Argument(msg, nameof(msg)).NotNull().MaxCount(32);
            Guard.Argument(blinding, nameof(blinding)).NotNull().MaxCount(32);

            using (var secp256k1 = new Secp256k1())
            {
                var msgHash = Cryptography.GenericHashNoKey(Encoding.UTF8.GetString(msg));
                return(secp256k1.Sign(msgHash, blinding));
            }
        }
Exemple #13
0
 public void Sign(string privateKey)
 {
     using (var sep = new Secp256k1())
     {
         var secret    = Convert.FromBase64String(privateKey);
         var hash      = Convert.FromBase64String(ComputeHash());
         var signature = new byte[64];
         sep.Sign(signature, hash, secret);
         Signature = Convert.ToBase64String(signature);
     }
 }
Exemple #14
0
        public void TestRecoverAddressTest()
        {
            var priKey     = "0xdce1443bd2ef0c2631adc1c67e5c93f13dc23a41c18b536effbbdcbcdb96fb65".ToBytes();
            var vechainKey = new SimpleWallet(priKey);

            var msgHash = Keccack256.CalculateHash("hello world");

            var signature = Secp256k1.Sign(msgHash, priKey);

            var recoverAddress = SimpleWallet.RecoverAddress(msgHash, signature);

            Assert.True(recoverAddress == "0x7567d83b7b8d80addcb281a71d54fc7b3364ffed");
        }
Exemple #15
0
        /// <summary>
        /// Sign a <paramref name="digest"/> using a <paramref name="privateKey"/>.
        /// </summary>
        /// <param name="digest">The digest to be signed.</param>
        /// <param name="privateKey">The private key.</param>
        /// <returns>The signature.</returns>
        public byte[] Sign(byte[] digest, byte[] privateKey)
        {
            if (digest == null)
            {
                throw new ArgumentNullException(nameof(digest));
            }
            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }

            return(_algorithm.Sign(privateKey, digest));
        }
Exemple #16
0
        /// <summary>
        /// Sign the specified amount and msg.
        /// </summary>
        /// <returns>The sign.</returns>
        /// <param name="amount">Amount.</param>
        /// <param name="msg">Message.</param>
        public byte[] Sign(ulong amount, byte[] msg)
        {
            Guard.Argument(msg, nameof(msg)).NotNull().MaxCount(32);

            using (var secp256k1 = new Secp256k1())
            {
                var blind   = DeriveKey(Version(), Stamp(), Password()).FromHex();
                var msgHash = Cryptography.GenericHashNoKey(Encoding.UTF8.GetString(msg));
                var sig     = secp256k1.Sign(msgHash, blind);

                return(sig);
            }
        }
        public void TestSecp256k1()
        {
            var priKey = Secp256k1.GeneratePrivateKey();
            var pubKey = Secp256k1.DerivePublicKey(priKey);

            var msgHash = Keccack256.CalculateHash("hello world");

            var signature = Secp256k1.Sign(msgHash, priKey);

            var recoveredPubKey = Secp256k1.RecoverPublickey(Keccack256.CalculateHash("hello world"), signature);

            Assert.True(pubKey.SequenceEqual(recoveredPubKey));
        }
Exemple #18
0
        /// <summary>
        /// Sign the specified amount, version, stamp, secret and msg.
        /// </summary>
        /// <returns>The sign.</returns>
        /// <param name="amount">Amount.</param>
        /// <param name="version">Version.</param>
        /// <param name="stamp">Stamp.</param>
        /// <param name="secret">secret.</param>
        /// <param name="msg">Message.</param>
        public byte[] Sign(ulong amount, int version, string stamp, SecureString secret, SecureString salt, byte[] msg)
        {
            Guard.Argument(stamp, nameof(stamp)).NotNull().NotEmpty();
            Guard.Argument(secret, nameof(secret)).NotNull();
            Guard.Argument(msg, nameof(msg)).NotNull().MaxCount(32);

            using (var secp256k1 = new Secp256k1())
            {
                var blind = DeriveKey(version, stamp, secret, salt).FromHex();
                var sig   = secp256k1.Sign(msg, blind);

                return(sig);
            }
        }
        public string GetSignature(string strToSign, string privateKey)
        {
            var secp256k1    = new Secp256k1();
            var messageBytes = Encoding.UTF8.GetBytes(strToSign);
            var messageHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes);
            var signature    = new byte[64];

            if (secp256k1.Sign(signature, messageHash, HexStringToByteArray(privateKey)))
            {
                return(ByteArrayToHexString(signature));
            }
            else
            {
                return(null);
            }
        }
Exemple #20
0
        /// <summary>
        /// Attaches the envelope.
        /// </summary>
        /// <param name="secp256k1">Secp256k1.</param>
        /// <param name="pedersen">Pedersen.</param>
        /// <param name="rangeProof">Range proof.</param>
        /// <param name="blindSum">Blind sum.</param>
        /// <param name="commitSum">Commit sum.</param>
        /// <param name="secret">Secret.</param>
        private void AttachEnvelope(Secp256k1 secp256k1, Pedersen pedersen, RangeProof rangeProof, byte[] blindSum, byte[] commitSum, ulong balance, SecureString secret)
        {
            var(k1, k2) = Split(blindSum, secret);

            Coin().Envelope.Commitment = commitSum.ToHex();
            Coin().Envelope.Proof      = k2.ToHex();
            Coin().Envelope.PublicKey  = pedersen.ToPublicKey(pedersen.Commit(0, k1)).ToHex();
            Coin().Hash = Hash(Coin()).ToHex();
            Coin().Envelope.Signature = secp256k1.Sign(Coin().Hash.FromHex(), k1).ToHex();

            proofStruct = rangeProof.Proof(0, balance, blindSum, commitSum, Coin().Hash.FromHex());

            var isVerified = rangeProof.Verify(commitSum, proofStruct);

            if (!isVerified)
            {
                throw new ArgumentOutOfRangeException(nameof(isVerified), "Range proof failed.");
            }
        }
Exemple #21
0
        public void SignTransaction(string secretKey)
        {
            var         secp256k1 = new Secp256k1();
            Span <byte> publicKey = new byte[64];

            secp256k1.PublicKeyCreate(publicKey, secretKey.ToBytes());

            //As only wallet owner can sign it's own transactions so
            //Public key genrated from secretKey must be equal to sender's wallet address (i.e. FromAddress)
            if (!publicKey.ToHex().Equals(FromAddress))
            {
                throw new Exception("You cannot sign transactions for other wallets.");
            }

            var         txHash    = CalculateHash();
            Span <byte> signature = new byte[64];

            secp256k1.Sign(signature, txHash, secretKey.ToBytes());
            Signature = signature.ToArray();
        }
Exemple #22
0
        /// <summary>
        /// Sign the specified amount and msg.
        /// </summary>
        /// <returns>The sign.</returns>
        /// <param name="amount">Amount.</param>
        /// <param name="msg">Message.</param>
        public byte[] Sign(ulong amount, byte[] msg)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(msg));
            }

            using (var secp256k1 = new Secp256k1())
            {
                var blind   = DeriveKey(Version(), Stamp(), Password()).FromHex();
                var msgHash = Cryptography.GenericHashNoKey(Encoding.UTF8.GetString(msg));
                var sig     = secp256k1.Sign(msgHash, blind);

                return(sig);
            }
        }
Exemple #23
0
        //Ignore this function as this is just to create Public Private key pairs for testing
        public static void GenerateKeys()
        {
            using (var secp256k1 = new Secp256k1())
            {
                // privatekey= "105c301c92f5d956ad577105e71aba4d29cf7af04cd47c648244dd8ad677381f"
                // publickey = "7a89dec4cc7e0964ed4c5e517f1cfee7e4f145e8500f55fe0317f97e71b7ba5219a4215b1885ac547da87bd0155d02c9bbe0501d0670a4f481df2b42f2130c02"

                // Generate a private key.
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256k1.SecretKeyVerify(privateKey));

                var prk = ToHex(privateKey);

                // Create public key from private key.
                var publicKey = new byte[64];
                Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey));

                var pbk = ToHex(publicKey);


                // Sign a message hash.
                var messageBytes = Encoding.UTF8.GetBytes("Hello world.");
                var messageHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes);
                var signature    = new byte[64];
                Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey));

                // Serialize a DER signature from ECDSA signature
                byte[] signatureDer = new byte[Secp256k1.SERIALIZED_DER_SIGNATURE_MAX_SIZE];
                int    outL         = 0;
                Debug.Assert(secp256k1.SignatureSerializeDer(signatureDer, signature, out outL));
                Array.Resize(ref signatureDer, outL);

                // Verify message hash.
                Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey));
            }
        }
Exemple #24
0
        /// <summary>
        /// Builds the coin.
        /// </summary>
        /// <returns>The coin.</returns>
        /// <param name="blindSum">Blind sum.</param>
        /// <param name="commitPos">Commit position.</param>
        /// <param name="commitNeg">Commit neg.</param>
        private CoinDto BuildCoin(byte[] blindSum, byte[] commitPos, byte[] commitNeg, bool receiver = false)
        {
            if (blindSum == null)
            {
                throw new ArgumentNullException(nameof(blindSum));
            }

            if (blindSum.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(blindSum));
            }

            if (commitPos == null)
            {
                throw new ArgumentNullException(nameof(commitPos));
            }

            if (commitPos.Length > 33)
            {
                throw new IndexOutOfRangeException(nameof(commitPos));
            }

            if (commitNeg == null)
            {
                throw new ArgumentNullException(nameof(commitNeg));
            }

            if (commitNeg.Length > 33)
            {
                throw new IndexOutOfRangeException(nameof(commitNeg));
            }

            CoinDto coin;
            bool    isVerified;

            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    var commitSum = pedersen.CommitSum(new List <byte[]> {
                        commitPos
                    }, new List <byte[]> {
                        commitNeg
                    });

                    isVerified = receiver
                    ? pedersen.VerifyCommitSum(new List <byte[]> {
                        commitPos, commitNeg
                    }, new List <byte[]> {
                        Commit((ulong)Output(), blindSum)
                    })
                    : pedersen.VerifyCommitSum(new List <byte[]> {
                        commitPos
                    }, new List <byte[]> {
                        commitNeg, commitSum
                    });

                    if (!isVerified)
                    {
                        throw new Exception(nameof(isVerified));
                    }

                    var(k1, k2) = Split(blindSum);

                    coin = MakeSingleCoin();

                    coin.Envelope.Commitment = commitSum.ToHex();
                    coin.Envelope.Proof      = k2.ToHex();
                    coin.Envelope.PublicKey  = pedersen.ToPublicKey(Commit(0, k1)).ToHex();
                    coin.Envelope.Signature  = secp256k1.Sign(Hash(coin), k1).ToHex();

                    coin.Hash = Hash(coin).ToHex();
                }

            return(coin);
        }
Exemple #25
0
        /// <summary>
        /// Builds the coin.
        /// </summary>
        /// <returns>The coin.</returns>
        /// <param name="blindSum">Blind sum.</param>
        /// <param name="commitPos">Commit position.</param>
        /// <param name="commitNeg">Commit neg.</param>
        private CoinDto BuildCoin(byte[] blindSum, byte[] commitPos, byte[] commitNeg, bool isReceiver = false)
        {
            Guard.Argument(blindSum, nameof(blindSum)).NotNull().MaxCount(32);
            Guard.Argument(commitPos, nameof(commitPos)).NotNull().MaxCount(33);
            Guard.Argument(commitNeg, nameof(commitNeg)).NotNull().MaxCount(33);

            CoinDto coin = null;
            bool    isVerified;

            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var rangeProof = new RangeProof())
                    {
                        try
                        {
                            var commitSum = pedersen.CommitSum(new List <byte[]> {
                                commitPos
                            }, new List <byte[]> {
                                commitNeg
                            });
                            var naTInput  = NaT(Input());
                            var naTOutput = NaT(Output());
                            var naTChange = naTInput - naTOutput;

                            isVerified = isReceiver
                        ? pedersen.VerifyCommitSum(new List <byte[]> {
                                commitPos, commitNeg
                            }, new List <byte[]> {
                                Commit(naTOutput, blindSum)
                            })
                        : pedersen.VerifyCommitSum(new List <byte[]> {
                                commitPos
                            }, new List <byte[]> {
                                commitNeg, commitSum
                            });

                            if (!isVerified)
                            {
                                throw new ArgumentOutOfRangeException(nameof(isVerified), "Verify commit sum failed.");
                            }

                            var(k1, k2) = Split(blindSum, isReceiver);

                            coin = MakeSingleCoin();

                            coin.Envelope.Commitment = isReceiver ? Commit(naTOutput, blindSum).ToHex() : commitSum.ToHex();
                            coin.Envelope.Proof      = k2.ToHex();
                            coin.Envelope.PublicKey  = pedersen.ToPublicKey(Commit(0, k1)).ToHex();
                            coin.Envelope.Signature  = secp256k1.Sign(Hash(coin), k1).ToHex();

                            coin.Hash = Hash(coin).ToHex();

                            proofStruct = isReceiver
                        ? rangeProof.Proof(0, naTOutput, blindSum, coin.Envelope.Commitment.FromHex(), coin.Hash.FromHex())
                        : rangeProof.Proof(0, naTChange, blindSum, coin.Envelope.Commitment.FromHex(), coin.Hash.FromHex());

                            isVerified = rangeProof.Verify(coin.Envelope.Commitment.FromHex(), proofStruct);

                            if (!isVerified)
                            {
                                throw new ArgumentOutOfRangeException(nameof(isVerified), "Range proof failed.");
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.LogError($"Message: {ex.Message}\n Stack: {ex.StackTrace}");
                        }
                    }

            return(coin);
        }