示例#1
0
        public static void Main(string[] args)
        {

            //Reading an existing file
            var address = "12890d2cce102216644c59dae5baed380d84830c";
            var password = "******";
            //UTC--2016-11-23T09-58-36Z--ca2137bc-e2a1-5c40-d60d-ab8cf5fb302c

            var file = File.OpenText("UTC--2016-11-23T09-58-36Z--ca2137bc-e2a1-5c40-d60d-ab8cf5fb302c");
           // var file = File.OpenText("UTC--2015-11-25T05-05-03.116905600Z--12890d2cce102216644c59dae5baed380d84830c");
            var json = file.ReadToEnd();
            
            //using the simple key store service
            var service = new KeyStoreService();
            //decrypt the private key
            var key = service.DecryptKeyStoreFromJson(password, json);
            
           //Generating a new file using the existing private key (key) 
           //create new file with the standard UTC file name
            var fileName = service.GenerateUTCFileName(address);
            using (var newfile = File.CreateText(fileName))
            {
                //generate the encrypted and key store content as json. (The default uses pbkdf2)
                var newJson = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, key, address);
                newfile.Write(newJson);
                newfile.Flush();
            }
            
            //Decrypting the new file created
            file = File.OpenText(fileName);
            json = file.ReadToEnd();

            var newkey = service.DecryptKeyStoreFromJson(password, json);

            //Compare the keys
            System.Console.WriteLine("Original key: " + key.ToHex());
            System.Console.WriteLine("New key: " + key.ToHex());
            System.Console.ReadLine();


            //We can use EthECKey to generate a new ECKey pair, this is using SecureRandom
            var ecKey = EthECKey.GenerateKey();
            var privateKey = ecKey.GetPrivateKeyAsBytes();
            var genAddress = ecKey.GetPublicAddress();

            //instead of the default service we can use either
            //Scrypt
            var scryptService = new KeyStoreScryptService();
            var scryptResult = scryptService.EncryptAndGenerateKeyStoreAsJson(password, privateKey, genAddress);
            //or pkbdf2
            var pbkdf2Service = new KeyStorePbkdf2Service();
            var pkbdf2Result = pbkdf2Service.EncryptAndGenerateKeyStoreAsJson(password, privateKey, genAddress);

            //Both services can be configured with a new IRandomBytesGenerator for the IV and Salt, currently uses SecureRandom for both.
            //also when encrypting we can pass custom KdfParameters
        }
示例#2
0
        public static void Main(string[] args)
        {
            //Reading an existing file
            var address  = "12890d2cce102216644c59dae5baed380d84830c";
            var password = "******";
            //UTC--2016-11-23T09-58-36Z--ca2137bc-e2a1-5c40-d60d-ab8cf5fb302c

            var file = File.OpenText("UTC--2016-11-23T09-58-36Z--ca2137bc-e2a1-5c40-d60d-ab8cf5fb302c");
            // var file = File.OpenText("UTC--2015-11-25T05-05-03.116905600Z--12890d2cce102216644c59dae5baed380d84830c");
            var json = file.ReadToEnd();

            //using the simple key store service
            var service = new KeyStoreService();
            //decrypt the private key
            var key = service.DecryptKeyStoreFromJson(password, json);

            //Generating a new file using the existing private key (key)
            //create new file with the standard UTC file name
            var fileName = service.GenerateUTCFileName(address);

            using (var newfile = File.CreateText(fileName))
            {
                //generate the encrypted and key store content as json. (The default uses pbkdf2)
                var newJson = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, key, address);
                newfile.Write(newJson);
                newfile.Flush();
            }

            //Decrypting the new file created
            file = File.OpenText(fileName);
            json = file.ReadToEnd();

            var newkey = service.DecryptKeyStoreFromJson(password, json);

            //Compare the keys
            System.Console.WriteLine("Original key: " + key.ToHex());
            System.Console.WriteLine("New key: " + key.ToHex());
            System.Console.ReadLine();


            //We can use EthECKey to generate a new ECKey pair, this is using SecureRandom
            var ecKey      = EthECKey.GenerateKey();
            var privateKey = ecKey.GetPrivateKeyAsBytes();
            var genAddress = ecKey.GetPublicAddress();

            //instead of the default service we can use either
            //Scrypt
            var scryptService = new KeyStoreScryptService();
            var scryptResult  = scryptService.EncryptAndGenerateKeyStoreAsJson(password, privateKey, genAddress);
            //or pkbdf2
            var pbkdf2Service = new KeyStorePbkdf2Service();
            var pkbdf2Result  = pbkdf2Service.EncryptAndGenerateKeyStoreAsJson(password, privateKey, genAddress);

            //Both services can be configured with a new IRandomBytesGenerator for the IV and Salt, currently uses SecureRandom for both.
            //also when encrypting we can pass custom KdfParameters
        }
示例#3
0
        public async Task <ECKeyPair> ReadKeyPairAsync(string address, string password)
        {
            try
            {
                var keyFilePath = GetKeyFileFullPath(address);
                var privateKey  = await Task.Run(() =>
                {
                    using (var textReader = File.OpenText(keyFilePath))
                    {
                        var json = textReader.ReadToEnd();
                        return(_keyStoreService.DecryptKeyStoreFromJson(password, json));
                    }
                });

                return(CryptoHelper.FromPrivateKey(privateKey));
            }
            catch (FileNotFoundException ex)
            {
                throw new KeyStoreNotFoundException("Keystore file not found.", ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw new KeyStoreNotFoundException("Invalid keystore path.", ex);
            }
            catch (DecryptionException ex)
            {
                throw new InvalidPasswordException("Invalid password.", ex);
            }
        }
示例#4
0
        //创建账号离线签名转账
        public async void createAccountFromKeyStory()
        {
            var path   = @"e:\UTC--2018-09-13T11-21-18.5956837Z--40ef545B54730D564424D8c629878c018D1999A9.json";
            var keySvc = new KeyStoreService();
            var json   = File.ReadAllText(path);
            var rkey   = keySvc.DecryptKeyStoreFromJson("123456", json);
            var addr   = keySvc.GetAddressFromKeyStore(json);

            Console.WriteLine("the ketStore account is{0}", addr);

            var web3  = new Web3("http://localhost:7545");
            var nonce = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(addr);

            var to     = "0x2BBA1062c3Ba7Fab710a96D68CF7d74B7830f679";
            var value  = new  BigInteger(2000000000000000000);
            var signed = "0x" + Web3.OfflineTransactionSigner.SignTransaction(rkey.ToHex(), to, value, nonce);

            var txhash = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync(signed);

            var receipt =
                await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(txhash);

            var balance = await web3.Eth.GetBalance.SendRequestAsync(addr);

            Console.WriteLine("the balance is{0}", balance.Value);
        }
        public static new CeloAccount LoadFromKeyStore(string json, string password, BigInteger?chainId = null)
        {
            var keyStoreService = new KeyStoreService();
            var key             = keyStoreService.DecryptKeyStoreFromJson(password, json);

            return(new CeloAccount(key, chainId));
        }
        public void LoadPrivateKey()
        {
            if (String.IsNullOrEmpty(Password))
            {
                throw new NullReferenceException("Password cannot be null or empty");
            }
            if (String.IsNullOrEmpty(FileName))
            {
                throw new NullReferenceException("File name cannot be null or empty");
            }
            if (!File.Exists(FileName))
            {
                throw new Exception("File cannot be found");
            }
            using (var file = System.IO.File.OpenText(FileName))
            {
                var json = file.ReadToEnd();
                //create a new Nethereum key store service
                var service = new KeyStoreService();
                //decrypt the json using the password and get the private key
                var privateKey = service.DecryptKeyStoreFromJson(Password, json).ToHex();

                var account = new Account(privateKey);
                accountsService.AddAccount(account);
            }
        }
示例#7
0
        /// <summary>
        ///     Loads the wallet from the filesystem
        /// </summary>
        /// <param name="json">The json string representing the encrypted wallet</param>
        /// <param name="passKey">The pass key to unlock the wallet</param>
        private void LoadFromKeyStore(string json, string passKey)
        {
            var keyStoreService = new KeyStoreService();
            var privateKey      = keyStoreService.DecryptKeyStoreFromJson(passKey, json);
            var key             = new EthECKey(privateKey, true);

            TransactionManager = new AccountSignerTransactionManager(null, key.GetPrivateKey(), ChainId);
        }
示例#8
0
        public static byte[] DecryptFromJson(string json, string password)
        {
            byte[]          privateKey = new byte[32];
            KeyStoreService keyStore   = new KeyStoreService();

            privateKey = keyStore.DecryptKeyStoreFromJson(password, json);
            return(privateKey);
        }
示例#9
0
        public static byte[] DecryptFromJson(Keystore keystore, string password)
        {
            byte[]          privateKey = new byte[32];
            KeyStoreService keyStore   = new KeyStoreService();

            privateKey = keyStore.DecryptKeyStoreFromJson(password, keystore.keystoreConvertToJson().ToString());
            return(privateKey);
        }
        public static Account DecryptAccount(string accountJsonFile, string passWord)
        {
            //using the simple key store service
            var service = new KeyStoreService();
            //decrypt the private key
            var key = service.DecryptKeyStoreFromJson(passWord, accountJsonFile);

            return(new Account(key));
        }
示例#11
0
        public static KeyStore Load(string password, string filePath)
        {
            var file = File.OpenText(filePath);
            var json = file.ReadToEnd();

            var privateKey = _keyStoreService.DecryptKeyStoreFromJson(password, json);
            var address    = _keyStoreService.GetAddressFromKeyStore(json);

            return(new KeyStore(new PrivateKey(privateKey), new ExternalAddress(address)));
        }
        public string GetPrivateKey(string path, string pass)
        {
            var file = File.OpenText(path);
            var json = file.ReadToEnd();

            //using the simple key store service
            var service = new KeyStoreService();

            return(service.DecryptKeyStoreFromJson(pass, json).ToHex());
        }
        public void ShouldGenerateAccountAndCreateKeyStoreFileDefaultService()
        {
            var ecKey           = Nethereum.Signer.EthECKey.GenerateKey();
            var keyStoreService = new KeyStoreService();
            var password        = "******";
            var json            = keyStoreService.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), ecKey.GetPublicAddress());
            var key             = keyStoreService.DecryptKeyStoreFromJson(password, json);

            Assert.Equal(ecKey.GetPrivateKey(), key.ToHex(true));
        }
示例#14
0
        public static void ImportWallet(string accountName, string password, string encryptedJson)
        {
            // Use key store service to re-generate the key
            var service = new KeyStoreService();

            byte[] bytes = service.DecryptKeyStoreFromJson(password, encryptedJson);
            var    ecKey = new EthECKey(bytes, true);

            // Created the wallet with given info
            AddWallet(accountName, ecKey.GetPublicAddress(), encryptedJson, ecKey.GetPrivateKey());
        }
        public Account LoadFromKeyStoreFile(string filePath, string password)
        {
            var keyStoreService = new KeyStoreService();

            if (!File.Exists(filePath))
            {
                throw new Exception("Account keystore file not found");
            }

            using (var file = File.OpenText(filePath))
            {
                var json = file.ReadToEnd();
                var key  = keyStoreService.DecryptKeyStoreFromJson(password, json);
                return(new Account(key));
            }
        }
示例#16
0
    private string GetPrivateKeyFromKeystore(string pass)
    {
        if (keystoreJSON == null || keystoreJSON == "" || pass == null || pass == "")
        {
            return("");
        }

        byte[]   b     = m_keystoreService.DecryptKeyStoreFromJson(pass, keystoreJSON);
        EthECKey myKey = new EthECKey(b, true);

        if (myKey.GetPublicAddress() != accountAddress)
        {
            return("");
        }

        return(myKey.GetPrivateKey());
    }
    public IEnumerator SendRawTransaction()
    {
        //unpack first
        string json = File.ReadAllText(@"ks");

        KeyStoreService keystore = new KeyStoreService();

        byte[] privateKey;
        try
        {
            privateKey = keystore.DecryptKeyStoreFromJson("", json);  //live
        }
        catch (DecryptionException exc)
        {
            Debug.Log("password invalid");
            throw exc;
        }


        int nonce = 1; // GetPending transaction count + 1;

        TransactionSigner signer = new TransactionSigner();
        string            signedTransactionData = signer.SignTransaction(privateKey, m_addr,
                                                                         new BigInteger(0.002f * m_ether),
                                                                         new BigInteger(nonce),
                                                                         new BigInteger(20L * m_gwei),
                                                                         new BigInteger(21000));

        Assert.IsTrue(signer.VerifyTransaction(signedTransactionData));

        Debug.Log(signer.GetSenderAddress(signedTransactionData));

        EthSendRawTransactionUnityRequest req = new EthSendRawTransactionUnityRequest(m_endpoint);

        yield return(req.SendRequest(signedTransactionData));

        Debug.Log(req.Result);
    }
示例#18
0
        /**
         * Second in series of element callbacks.
         * Save visual element properties, parse and prepare dynamic calls for CONTRACT_PARAMS property
         */
        public void OnNodeInit(Hashtable elements, IPlugin element)
        {
            // Provider url ("http://localhost:8545")
            _providerUrl = element.GetElementProperty("PROVIDER_URL");

            // Message value ("0"). Number of wei sent with the message.
            _messageValue = element.GetElementProperty("MESSAGE_VALUE");

            // Default gas value. ("290000")
            _defaultGas = string.IsNullOrEmpty(element.GetElementProperty("DEFAUT_GAS")) ?
                          "290000" :
                          element.GetElementProperty("DEFAUT_GAS");

            // Smart contract address ("0x97a93e68fa58513facb2b702a97597cab97afd6f")
            _contractAddress = element.GetElementProperty("SMART_CONTRACT_ADDRESS");

            // Smart contract ABI ([{""constant"":false,""inputs"":[{""name"":""tvConsumption"",""type"":""int256""},
            //                      {""name"":""washingMachineConsumption"",""type"":""int256""}],""name"":""saveConsumptions"",""outputs"":[],
            //                      ""payable"":false,""stateMutability"":""nonpayable"",""type"":""function""},{""constant"":false,""inputs"":[],
            //                      ""name"":""getConsumptions"",""outputs"":[{""name"":""sumConsumption"",""type"":""int256""}],""payable"":false,
            //                      ""stateMutability"":""nonpayable"",""type"":""function""},{""inputs"":[{""name"":""tvConsumption"",""type"":""int256""},
            //                      {""name"":""washingMachineConsumption"",""type"":""int256""}],""payable"":false,""stateMutability"":""nonpayable"",
            //                      ""type"":""constructor""}])
            _abi = ZenCsScriptCore.Decode(element.GetElementProperty("ABI"));

            // Name of smart contract function to be called ("saveConsumptions")
            _functionName = element.GetElementProperty("FUNCTION_NAME");

            // Get private key from keystore file
            var json    = File.OpenText(element.GetElementProperty("KEYSTORE_FILE")).ReadToEnd();
            var service = new KeyStoreService();

            _privateKey = service.DecryptKeyStoreFromJson(element.GetElementProperty("KEYSTORE_FILE_PASSWORD"), json).ToHex();
            _address    = service.GetAddressFromKeyStore(json);

            // Parse result tags (<result>Element Id</result>) defined by user and dynamically create assembly that will query element results.
            InitializeScript(elements, element);
        }
示例#19
0
        private void Create(object obj)
        {
            if (String.IsNullOrWhiteSpace(Passphrase))
            {
                MessageBox.Show("Passphrase must be entered.", "Wallet", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (Passphrase.Length < 10)
            {
                MessageBox.Show("Passphrase must be at least 10 characters long.", "Wallet", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (String.IsNullOrWhiteSpace(SavePath))
            {
                MessageBox.Show("Please select a file location to save your wallet to.", "Wallet", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (File.Exists(SavePath))
            {
                if (MessageBox.Show(
                        "There is already an existing wallet at " + SavePath +
                        ".\r\nAre you sure you want to overwrite it?", "Wallet", MessageBoxButton.YesNo,
                        MessageBoxImage.Error) == MessageBoxResult.No)
                {
                    return;
                }
            }

            var folder = Directory.GetParent(SavePath);

            folder.Create();

            IsBusy = true;

            Task.Run(() =>
            {
                var publicAddress = AppVM.Geth.Personal.NewAccount.SendRequestAsync(Passphrase).GetAwaiter().GetResult();

                var service = new KeyStoreService();

                var nodeFolder = Task.Run(() => AppVM.Geth.Admin.Datadir.SendRequestAsync()).Result;

                var keyStoreFolder = Path.Combine(nodeFolder, "keysotres");

                if (!Directory.Exists(keyStoreFolder))
                {
                    keyStoreFolder = Path.Combine(nodeFolder, "keystores");
                }

                if (!Directory.Exists(keyStoreFolder))
                {
                    Application.Current.Dispatcher.Invoke(() => IsBusy = false);
                    Application.Current.Dispatcher.Invoke(() => MessageBox.Show("Error finding keystore folder.", "Wallet", MessageBoxButton.OK, MessageBoxImage.Error));
                    return;
                }

                var files = Directory.GetFiles(keyStoreFolder, "*.*", SearchOption.TopDirectoryOnly);

                string selectedFilePath = null;

                foreach (var file in files)
                {
                    var address = service.GetAddressFromKeyStore(File.ReadAllText(file));

                    if (address == publicAddress.Substring(2))
                    {
                        selectedFilePath = file;
                        break;
                    }
                }

                if (String.IsNullOrWhiteSpace(selectedFilePath))
                {
                    Application.Current.Dispatcher.Invoke(() => IsBusy = false);
                    Application.Current.Dispatcher.Invoke(() => MessageBox.Show("Failed to create wallet", "Wallet", MessageBoxButton.OK, MessageBoxImage.Error));
                    return;
                }

                File.Copy(selectedFilePath, SavePath, true);

                var bytes = service.DecryptKeyStoreFromJson(Passphrase, File.ReadAllText(SavePath));

                foreach (var file in files)
                {
                    if (file != selectedFilePath)
                    {
                        File.Delete(file);
                    }
                }

                Application.Current.Dispatcher.Invoke(() =>
                {
                    PublicAddress    = publicAddress;
                    PrivateKey       = bytes.ToHex(true);
                    ShowPrivateKey   = true;
                    ShowCreateButton = false;
                    ShowCloseButton  = true;
                    IsBusy           = false;
                });
            });
        }