public void SignCompressedCompactTest()
        {
            var key  = Secp256K1Manager.GenerateRandomKey();
            var sw1  = new Stopwatch();
            var rand = new RNGCryptoServiceProvider();

            byte[] msg;
            for (int i = 1; i < 1000; i++)
            {
                msg = new byte[i];
                rand.GetBytes(msg);

                var hash = Sha256Manager.GetHash(msg);

                sw1.Start();
                var signature1 = Secp256K1Manager.SignCompressedCompact(hash, key);
                sw1.Stop();

                Assert.True(signature1.Length == 65);
                Assert.True(Secp256K1Manager.IsCanonical(signature1, 1));
                if (!Secp256K1Manager.IsCanonical(signature1, 1))
                {
                    WriteLine($"signature1 not canonical - skip [{i}]");
                }
            }

            WriteLine($"Secp256K1Manager time {sw1.ElapsedTicks}");
        }
Example #2
0
        public static string GetVakaPublicKey(string privatekey)
        {
            var privateBytes = WifUtility.DecodePrivateWif(privatekey);
            var publicKey    = Secp256K1Manager.GetPublicKey(privateBytes, true);

            return(WifUtility.GetPublicWif(publicKey, "VAKA"));
        }
Example #3
0
        public static Wallet Generate(bool compressed)
        {
            byte[] randomKey = Secp256K1Manager.GenerateRandomKey();
            byte[] array1    = ((IEnumerable <byte>) new byte[1]).Concat <byte>((IEnumerable <byte>)Ripemd160Manager.GetHash(Sha256Manager.GetHash(Secp256K1Manager.GetPublicKey(randomKey, compressed)))).ToArray <byte>();
            string pub       = Base58.Encode(((IEnumerable <byte>)array1).Concat <byte>(((IEnumerable <byte>)Sha256Manager.GetHash(Sha256Manager.GetHash(array1))).Take <byte>(4)).ToArray <byte>());

            byte[] array2;
            if (!compressed)
            {
                array2 = ((IEnumerable <byte>) new byte[1]
                {
                    (byte)128
                }).Concat <byte>((IEnumerable <byte>)randomKey).ToArray <byte>();
            }
            else
            {
                array2 = ((IEnumerable <byte>) new byte[1]
                {
                    (byte)128
                }).Concat <byte>((IEnumerable <byte>)randomKey).Concat <byte>((IEnumerable <byte>) new byte[1]
                {
                    (byte)1
                }).ToArray <byte>();
            }
            return(new Wallet(Base58.Encode(((IEnumerable <byte>)array2).Concat <byte>(((IEnumerable <byte>)Sha256Manager.GetHash(Sha256Manager.GetHash(array2))).Take <byte>(4)).ToArray <byte>()), pub));
        }
Example #4
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World2!");
            var message = "Here's a message";

            byte[] msg    = Encoding.UTF8.GetBytes(message);
            var    seckey = Hex.HexToBytes("c57ca12c10652293ca4fa61f3ee90d6896cf695d7b7891263e2f01cf2fa61cf8");
            var    data   = Sha256Manager.GetHash(msg);
            //var dataHex = Encoding.UTF8.GetChars(data);
            //Console.WriteLine(dataHex);
            //var sha = new SHA3.SHA3Managed(256);
            //sha.ComputeHash(msg);
            //Console.WriteLine(sha.HashByteLength);
            //var data = Encoding.UTF8.GetBytes(sha.ToString());
            //var data = sha.Hash;
            //var hash = HashFactory.Crypto.SHA3.CreateKeccak256();
            //var res = hash.ComputeString(message, Encoding.UTF8);
            //Console.WriteLine(res);
            //var data = res.GetBytes();
            var recoveryId = 24;
            //var sig = Secp256K1Manager.SignCompressedCompact(data, seckey);
            var sig       = Secp256K1Manager.SignCompact(data, seckey, out recoveryId);
            var signature = Hex.ToString(sig);

            Console.WriteLine(signature);
        }
Example #5
0
        public void GenerateKeys()
        {
            WriteLine("password key:");
            var privateKey = Secp256K1Manager.GenerateRandomKey();
            var privateWif = "P" + Base58.EncodePrivateWif(privateKey);

            WriteLine(privateWif);
            WriteLine(Hex.ToString(privateKey));

            var publicKey       = Secp256K1Manager.GetPublicKey(privateKey, true);
            var encodePublicWif = Base58.EncodePublicWif(publicKey, "STM");

            WriteLine(encodePublicWif);
            WriteLine(Hex.ToString(publicKey));

            var name = "userlogin";

            string[] roles = { "posting", "active", "owner", "memo" };

            foreach (var role in roles)
            {
                WriteLine(role);
                var subWif = Base58.GetSubWif(name, privateWif, role);
                WriteLine(subWif);
                var pk = Base58.DecodePrivateWif(subWif);
                WriteLine(Hex.ToString(pk));
                var subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);
                var publicWif    = Base58.EncodePublicWif(subPublicKey, "STM");
                WriteLine(publicWif);
                WriteLine(Hex.ToString(subPublicKey));
            }
        }
Example #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="propertyApiObj"></param>
        /// <param name="userPrivateKeys"></param>
        /// <param name="token">Throws a <see cref="T:System.OperationCanceledException" /> if this token has had cancellation requested.</param>
        /// <param name="operations"></param>
        /// <returns></returns>
        /// <exception cref="T:System.OperationCanceledException">The token has had cancellation requested.</exception>
        public Task <SignedTransaction> CreateTransactionAsync(DynamicGlobalPropertyObject propertyApiObj, IList <byte[]> userPrivateKeys, BaseOperation[] operations, CancellationToken token)
        {
            return(Task.Run(() =>
            {
                var transaction = new SignedTransaction
                {
                    ChainId = ChainId,
                    RefBlockNum = (ushort)(propertyApiObj.HeadBlockNumber & 0xffff),
                    RefBlockPrefix = (uint)BitConverter.ToInt32(Hex.HexToBytes(propertyApiObj.HeadBlockId), 4),
                    Expiration = propertyApiObj.Time.Value.AddSeconds(30),
                    Operations = operations.Select(o => new Operation(o)).ToArray()
                };

                var msg = MessageSerializer.Serialize <SignedTransaction>(transaction);
                var data = Sha256Manager.GetHash(msg);

                transaction.Signatures = new string[userPrivateKeys.Count];
                for (var i = 0; i < userPrivateKeys.Count; i++)
                {
                    token.ThrowIfCancellationRequested();
                    var userPrivateKey = userPrivateKeys[i];
                    var sig = Secp256K1Manager.SignCompressedCompact(data, userPrivateKey);
                    transaction.Signatures[i] = Hex.ToString(sig);
                }

                return transaction;
            }, token));
        }
        public DefaultSignProvider(string privateKey)
        {
            var privKeyBytes = CryptoHelper.GetPrivateKeyBytesWithoutCheckSum(privateKey);
            var pubKey       = CryptoHelper.PubKeyBytesToString(Secp256K1Manager.GetPublicKey(privKeyBytes, true));

            Keys.Add(pubKey, privKeyBytes);
        }
Example #8
0
        private void VerifyWif(UserInfo user)
        {
            var pkBytes = Secp256K1Manager.GetPublicKey(user.ActiveKeys[0], true);
            var pk      = new PublicKeyType(pkBytes, SbdSymbol);

            Assert.True(pk.Data.SequenceEqual(user.Account.Active.KeyAuths[0].Key.Data));
        }
Example #9
0
        private (byte[], byte[]) GenerateKeyPair()
        {
            var privateKey = Secp256K1Manager.GenerateRandomKey();
            var publicKey  = Secp256K1Manager.GetPublicKey(privateKey, compressed: true);

            return(publicKey, privateKey);
        }
        public Task <IEnumerable <string> > Sign(string chainId, IEnumerable <string> requiredKeys, byte[] signBytes,
                                                 IEnumerable <string> abiNames = null)
        {
            var data = new List <byte[]>()
            {
                Hex.HexToBytes(chainId),
                signBytes,
                new byte[32]
            };

            var hash = Sha256Manager.GetHash(SerializationHelper.Combine(data));

            return(Task.FromResult(requiredKeys.Select(key =>
            {
                var sign = Secp256K1Manager.SignCompressedCompact(hash, Keys[key]);
                var check = new List <byte[]>()
                {
                    sign, KeyTypeBytes
                };
                var checksum = Ripemd160Manager.GetHash(SerializationHelper.Combine(check)).Take(4).ToArray();
                var signAndChecksum = new List <byte[]>()
                {
                    sign, checksum
                };

                return "SIG_K1_" + Base58.Encode(SerializationHelper.Combine(signAndChecksum));
            })));
        }
Example #11
0
        public void GetPublicKeyTest(string privateKey, string expectedPubKey)
        {
            var pk        = Base58.DecodePrivateWif(privateKey);
            var publicKey = Secp256K1Manager.GetPublicKey(pk, true);
            var pWif      = Base58.EncodePublicWif(publicKey, "STM");

            Assert.Equal(expectedPubKey, pWif);
        }
Example #12
0
        private byte[] sign(byte[] msgHash, byte[] privateKey)
        {
            var recovery = 0;
            var sig      = Secp256K1Manager.SignCompact(msgHash, privateKey, out recovery);
            var _recBuf  = recovery.ToString("x").HexToByteArray();
            var ret      = ByteUtil.Merge(sig, _recBuf);

            return(ret);
        }
Example #13
0
        private (PrivateKey PrivateKey, PublicKey PublicKey, Address Address) Create(bool compress = true)
        {
            var privateKeyBytes = Secp256K1Manager.GenerateRandomKey();
            var publicKeyBytes  = Secp256K1Manager.GetPublicKey(privateKeyBytes, compress).Skip(1).ToArray();
            var publicKeyHash   = Sha256Manager.GetHash(publicKeyBytes);
            var addressBytes    = publicKeyHash.Skip(12).ToArray();

            return(new PrivateKey(privateKeyBytes), new PublicKey(publicKeyBytes, compress), new Address(addressBytes));
        }
 public static bool IsValid(
     // ReSharper disable once ParameterTypeCanBeEnumerable.Global
     byte[] publicKey,
     byte[] privateKey)
 {
     return(Secp256K1Manager
            .GetPublicKey(privateKey, true)
            .SequenceEqual(publicKey));
 }
Example #15
0
 public void Sign(byte[] privKey, byte[] pubKey)
 {
     byte[] pub = pubKey;
     if (pubKey == null)
     {
         pub = Secp256K1Manager.GetPublicKey(privKey, true);
     }
     this.GtxObject.Sign(privKey, pub);
 }
Example #16
0
        /// <summary>
        /// Gets the public key.
        /// </summary>
        /// <returns>The public key.</returns>
        public PublicKey GetPublicKey()
        {
            var pubKeyByes = Secp256K1Manager.GetPublicKey(this.D.ToByteArrayUnsigned(true), true);

            return(new PublicKey()
            {
                Data = pubKeyByes
            });
        }
Example #17
0
        public static byte[] GetPublicKey(byte[] privateKey, bool compressed)
        {
            var originalkeyBytes = Secp256K1Manager.GetPublicKey(privateKey, compressed);
            var validKeyBytes    = new byte[originalkeyBytes.Length - 1];

            Buffer.BlockCopy(originalkeyBytes, 1, validKeyBytes, 0, validKeyBytes.Length);

            return(validKeyBytes);
        }
Example #18
0
        public static KeyPair GenerateKeyPair()
        {
            KeyPair keyPair = new KeyPair();

            byte[] privateKey = Secp256K1Manager.GenerateRandomKey();
            keyPair.PrivateKey = WifUtility.GetPrivateWif(privateKey);
            byte[] publicKey = Secp256K1Manager.GetPublicKey(privateKey, true);
            keyPair.PublicKey = WifUtility.GetPublicWif(publicKey, "EOS");
            return(keyPair);
        }
Example #19
0
        public string GetPublicKey()
        {
            var publicKeyBytes  = Secp256K1Manager.GetPublicKey(Key, true);
            var checksum        = GetChecksum(publicKeyBytes);
            var keyWithChecksum = new[] { publicKeyBytes, checksum };

            var publicKey = Base58.Encode(keyWithChecksum.Flattern());

            return($"EOS{publicKey}");
        }
Example #20
0
        public async Task <PushTransaction> PushTransactionAsync(Action[] actions, List <string> privateKeysInWIF)
        {
            logger.Debug("GetInfoAsync");
            //get info
            var info = await GetInfoAsync();

            logger.Debug("GetBlockAsync");
            //get head block
            var block = await GetBlockAsync(info.head_block_id);

            //prepare transaction object
            var transaction = new EOSNewYork.EOSCore.Params.Transaction {
                actions          = actions,
                ref_block_num    = (ushort)(block.block_num & 0xffff),
                ref_block_prefix = block.ref_block_prefix,
                expiration       = new TimePointSec(block.timestamp_datetime.AddSeconds(delaySec))
            };

            //pack the transaction
            var packedTransaction = new PackingSerializer().Serialize <EOSNewYork.EOSCore.Params.Transaction>(transaction);

            //get chain id
            var chainId = Hex.HexToBytes(info.chain_id);

            //combine chainId, packed transaction and 32 empty bytes
            var message = new byte[chainId.Length + packedTransaction.Length + 32];

            Array.Copy(chainId, message, chainId.Length);
            Array.Copy(packedTransaction, 0, message, chainId.Length, packedTransaction.Length);

            //calculate message hash
            var messageHash = Sha256Manager.GetHash(message);

            //get private keys in WIF format
            List <byte[]> privateKeys = new List <byte[]>();

            for (int i = 0; i < privateKeysInWIF.Count; i++)
            {
                privateKeys.Add(WifUtility.DecodePrivateWif(privateKeysInWIF[i]));
            }

            //get signatures for each private key by signing message hash with private key
            string[] signatures = new string[privateKeys.Count];
            for (int i = 0; i < privateKeys.Count; i++)
            {
                signatures[i] = WifUtility.EncodeSignature(Secp256K1Manager.SignCompressedCompact(messageHash, privateKeys[i]));
            }

            logger.Debug("push transaction - GetObjectsFromAPIAsync");
            //push transaction
            return(await new EOS_Object <PushTransaction>(HOST).GetObjectsFromAPIAsync(new PushTransactionParam {
                packed_trx = Hex.ToString(packedTransaction), signatures = signatures, packed_context_free_data = string.Empty, compression = "none"
            }));
        }
Example #21
0
        public static KeyPair GenerateKeyPair(string keyType = null)
        {
            var key    = Secp256K1Manager.GenerateRandomKey();
            var pubKey = Secp256K1Manager.GetPublicKey(key, true);

            return(new KeyPair()
            {
                PrivateKey = KeyToString(key, keyType, keyType == "R1" ? "PVT_R1_" : null),
                PublicKey = KeyToString(pubKey, keyType, keyType == "R1" ? "PUB_R1_" : "EOS")
            });
        }
Example #22
0
        private static void Callback(object state)
        {
            var ts = GetReconectToken();

            TryRunTask(TryСonect, ts);
            // static constructor initialization.
            var init = new Secp256K1Manager();

            AppSettings.LocalizationManager.Update(Api.Gateway);
            LazyLoadTimer.Dispose();
        }
Example #23
0
        public async Task AccountCreateOperationTest()
        {
            var name = $"ditch-test-user-{DateTime.Now.Ticks}";

            WriteLine($"name: {name}");
            var key  = Secp256K1Manager.GenerateRandomKey();
            var pwif = "P" + Base58.EncodePrivateWif(key);

            WriteLine($"pwif: {pwif}");

            var user   = User;
            var userId = user.Account.Id;

            var op = new AccountCreateOperation
            {
                Fee = new Asset
                {
                    Amount  = 500000,
                    AssetId = new AssetIdType(1, 3, 0)
                },
                Registrar       = userId,
                Referrer        = userId,
                ReferrerPercent = 10000,
                Name            = name,
                Options         = new AccountOptions
                {
                    VotingAccount = new AccountIdType(1, 2, 5)
                }
            };

            var subWif = Base58.GetSubWif(name, pwif, "owner");

            WriteLine($"owner: {subWif}");
            var pk           = Base58.DecodePrivateWif(subWif);
            var subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);

            op.Owner = new Authority(new PublicKeyType(subPublicKey, SbdSymbol));

            subWif = Base58.GetSubWif(name, pwif, "active");
            WriteLine($"active: {subWif}");
            pk           = Base58.DecodePrivateWif(subWif);
            subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);
            op.Active    = new Authority(new PublicKeyType(subPublicKey, SbdSymbol));

            subWif = Base58.GetSubWif(name, pwif, "memo");
            WriteLine($"memo: {subWif}");
            pk                 = Base58.DecodePrivateWif(subWif);
            subPublicKey       = Secp256K1Manager.GetPublicKey(pk, true);
            op.Options.MemoKey = new PublicKeyType(subPublicKey, SbdSymbol);


            await Post(user.ActiveKeys, false, op).ConfigureAwait(false);
        }
Example #24
0
        public Signature(StdMsg stdMsg, byte[] privateKey)
        {
            pub_key = new PubKey(privateKey);

            var stdMsgJObj       = JObject.FromObject(stdMsg.input);
            var stdMsgJObjSorted = Utils.JSON.Sort(stdMsgJObj);
            var messageJSON      = JsonConvert.SerializeObject(stdMsgJObjSorted);
            var messageBytes     = Encoding.UTF8.GetBytes(messageJSON);
            var messageHashBytes = SHA256.Create().ComputeHash(messageBytes);
            var signBytes        = Secp256K1Manager.SignCompact(messageHashBytes, privateKey, out _);

            signature = Convert.ToBase64String(signBytes);
        }
        public DefaultSignProvider(List <string> privateKeys)
        {
            if (privateKeys == null || privateKeys.Count == 0)
            {
                throw new ArgumentNullException("privateKeys");
            }

            foreach (var key in privateKeys)
            {
                var privKeyBytes = CryptoHelper.GetPrivateKeyBytesWithoutCheckSum(key);
                var pubKey       = CryptoHelper.PubKeyBytesToString(Secp256K1Manager.GetPublicKey(privKeyBytes, true));
                Keys.Add(pubKey, privKeyBytes);
            }
        }
Example #26
0
        public async Task WalletImportKeyTest()
        {
            var user = new UserInfo
            {
                Login = $"testname{DateTime.Now:yyyyMMddhhmmss}"
            };

            WriteLine(user.Login);
            var resp = await Api.WalletCreate(user.Login, CancellationToken.None);

            WriteLine(resp);
            Assert.IsFalse(resp.IsError);
            user.Password = resp.Result;

            var key1 = Secp256K1Manager.GenerateRandomKey();

            user.PrivateOwnerWif = Core.Base58.EncodePrivateWif(key1);
            var pKey1 = Secp256K1Manager.GetPublicKey(key1, true);

            user.PublicOwnerWif = Core.Base58.EncodePublicWif(pKey1, "EOS");

            var key2 = Secp256K1Manager.GenerateRandomKey();

            user.PrivateActiveWif = Core.Base58.EncodePrivateWif(key2);
            var pKey2 = Secp256K1Manager.GetPublicKey(key2, true);

            user.PublicActiveWif = Core.Base58.EncodePublicWif(pKey2, "EOS");

            WriteLine(user);

            var addOwner = await Api.WalletImportKey(user.Login, user.PrivateOwnerWif, CancellationToken.None);

            WriteLine(addOwner);
            Assert.IsFalse(resp.IsError);

            var addActive = await Api.WalletImportKey(user.Login, user.PrivateActiveWif, CancellationToken.None);

            WriteLine(addActive);
            Assert.IsFalse(resp.IsError);

            var unlock = await Api.WalletUnlock(user.Login, user.Password, CancellationToken);

            Assert.IsFalse(unlock.IsError);

            var walletGetPublicKeysResult = await Api.WalletGetPublicKeys(CancellationToken.None);

            WriteLine(walletGetPublicKeysResult);
            Assert.IsFalse(walletGetPublicKeysResult.IsError);
        }
Example #27
0
        public Signature Sign(IEnumerable <byte> data, PrivateKey privateKey)
        {
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data), "Data can not be null");
            }

            if (privateKey is null)
            {
                throw new ArgumentNullException(nameof(privateKey), "Private key can not be null");
            }

            var signature = Secp256K1Manager.SignCompressedCompact(data.ToArray(), privateKey.Bytes);

            return(new Signature(signature));
        }
Example #28
0
        /// <summary>
        /// Generate a new key pair based on a key type
        /// </summary>
        /// <param name="keyType">Optional key type. (sha256x2, R1)</param>
        /// <returns>key pair</returns>
        public static KeyPair GenerateKeyPair(string keyType = "sha256x2")
        {
            var key    = Secp256K1Manager.GenerateRandomKey();
            var pubKey = Secp256K1Manager.GetPublicKey(key, true);

            if (keyType != "sha256x2" && keyType != "R1")
            {
                throw new Exception("invalid key type.");
            }

            return(new KeyPair()
            {
                PrivateKey = KeyToString(key, keyType, keyType == "R1" ? "PVT_R1_" : null),
                PublicKey = KeyToString(pubKey, keyType != "sha256x2" ? keyType : null, keyType == "R1" ? "PUB_R1_" : "EOS")
            });
        }
Example #29
0
        public async Task AccountCreateTest()
        {
            const string name = "userlogin";

            var op = new AccountCreateOperation
            {
                Fee            = new Asset(3000, 3, "GBG"),
                Creator        = User.Login,
                NewAccountName = User.Login,
                JsonMetadata   = ""
            };

            var privateKey = Secp256K1Manager.GenerateRandomKey();
            var privateWif = "12345678"; //"P" + Base58.EncodePrivateWif(privateKey);

            var subWif = Base58.GetSubWif(name, privateWif, "owner");

            Console.WriteLine(subWif);
            var pk           = Base58.DecodePrivateWif(subWif);
            var subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);

            Console.WriteLine(Base58.EncodePublicWif(subPublicKey, Config.KeyPrefix));
            op.Owner.KeyAuths.Add(new KeyValuePair <PublicKeyType, ushort>(new PublicKeyType(subPublicKey), 1));

            subWif = Base58.GetSubWif(name, privateWif, "active");
            Console.WriteLine(subWif);
            pk           = Base58.DecodePrivateWif(subWif);
            subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);
            Console.WriteLine(Base58.EncodePublicWif(subPublicKey, Config.KeyPrefix));
            op.Active.KeyAuths.Add(new KeyValuePair <PublicKeyType, ushort>(new PublicKeyType(subPublicKey), 1));

            subWif = Base58.GetSubWif(name, privateWif, "posting");
            Console.WriteLine(subWif);
            pk           = Base58.DecodePrivateWif(subWif);
            subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);
            Console.WriteLine(Base58.EncodePublicWif(subPublicKey, Config.KeyPrefix));
            op.Posting.KeyAuths.Add(new KeyValuePair <PublicKeyType, ushort>(new PublicKeyType(subPublicKey), 1));

            subWif = Base58.GetSubWif(name, privateWif, "memo");
            Console.WriteLine(subWif);
            pk           = Base58.DecodePrivateWif(subWif);
            subPublicKey = Secp256K1Manager.GetPublicKey(pk, true);
            Console.WriteLine(Base58.EncodePublicWif(subPublicKey, Config.KeyPrefix));
            op.MemoKey = new PublicKeyType(subPublicKey);

            await Post(User.ActiveKeys, false, op).ConfigureAwait(false);
        }
Example #30
0
        public void GenerateKeys()
        {
            var pk         = Secp256K1Manager.GenerateRandomKey();
            var privateWif = Base58.EncodePrivateWif(pk);

            Console.WriteLine($"private owner: {privateWif}");
            var pubKey    = Secp256K1Manager.GetPublicKey(pk, true);
            var publicWif = Base58.EncodePublicWif(pubKey, "EOS");

            Console.WriteLine($"public owner: {publicWif}");

            pk         = Secp256K1Manager.GenerateRandomKey();
            privateWif = Base58.EncodePrivateWif(pk);
            Console.WriteLine($"private active: {privateWif}");
            pubKey    = Secp256K1Manager.GetPublicKey(pk, true);
            publicWif = Base58.EncodePublicWif(pubKey, "EOS");
            Console.WriteLine($"public active: {publicWif}");
        }