public string CreateAccount(string password) { //Generate a private key pair using SecureRandom var ecKey = EthECKey.GenerateKey(); //Get the public address (derivied from the public key) var address = ecKey.GetPublicAddress(); var privateKey = ecKey.GetPrivateKey(); //Create a store service, to encrypt and save the file using the web3 standard var service = new KeyStoreService(); //var encryptedKey = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), address); string result = "{" + "\"Private Key\"" + ":" + "\"" + privateKey + "\"" + "," + "\"Address\"" + ":" + "\"" + address + "\"" + "," + "\"password\"" + ":" + "\"" + password + "\"" + "}"; /********If you want to save the wallet address and private key as a keystore file, * you can use the below code * * Produced by Josiah * * ***********/ /******* var fileName = service.GenerateUTCFileName(address) + ".key"; * var fileName = address + ".key"; * using (var newfile = File.CreateText(Path.Combine(path, fileName))) * { * newfile.Write(encryptedKey); * newfile.Flush(); * } * **********/ return(result); }
//创建账号离线签名转账 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 void CreateHDWallet() { // 通过已知的助记词生成账号 var wallet = new Wallet(Words, Password); var account = wallet.GetAccount(0); Console.WriteLine(account.Address); var prk = wallet.GetPrivateKey(account.Address);//获取账号对应的秘钥 var accprk = account.PrivateKey; Console.WriteLine("the prk is {0}", prk.ToHex()); Console.WriteLine("the accprk is {0}", accprk); // 第一次创建钱包 生成随机的助记词 并保存 var mnemonic = new Mnemonic(Wordlist.English, WordCount.Twelve); Console.WriteLine(mnemonic.ToString()); var masterKey = mnemonic.DeriveExtKey("123456"); //生成一组组秘钥对 可以通过该秘钥继续生成子孙密钥对 var privateKey = masterKey.PrivateKey; //获取的是bitcoin的私钥 var wallet1 = new Wallet(mnemonic.ToString(), "123456"); Console.WriteLine("the wallet1 mnemonic is {0}", mnemonic.ToString()); var account1 = wallet1.GetAccount(0); Console.WriteLine("the wallet1 account is {0}", account1.Address); var keySvc = new KeyStoreService(); var json = keySvc.EncryptAndGenerateDefaultKeyStoreAsJson("123456", account1.PrivateKey.HexToByteArray(), account1.Address); var path = string.Format(@"e:\{0}.json", keySvc.GenerateUTCFileName(account1.Address)); File.WriteAllText(path, json); }
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); } }
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 RpcApiResult BackupWallet(string password) { if (password.IsNullOrEmpty()) { return(new RpcApiResult(false, RpcMessage.INVALID_PASSWORD, "Invalid password.")); } if (!KeyStoreService.DecryptKeyStore(password, RpcApi.KeyStore, out byte[] privatekey))
/// <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); }
public AElfKeyStore(INodeEnvironmentService nodeEnvironmentService) { _nodeEnvironmentService = nodeEnvironmentService; _unlockedAccounts = new List <Account>(); _keyStoreService = new KeyStoreService(); Logger = NullLogger <AElfKeyStore> .Instance; }
public static byte[] DecryptFromJson(string json, string password) { byte[] privateKey = new byte[32]; KeyStoreService keyStore = new KeyStoreService(); privateKey = keyStore.DecryptKeyStoreFromJson(password, json); 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)); }
public Task RestoreAccountByKey(string privateKey, string newPassword) { return(Task.Run(() => { this.Account = new Account(privateKey); var json = new KeyStoreService().EncryptAndGenerateDefaultKeyStoreAsJson(newPassword, privateKey.HexToByteArray(), this.Account.Address); Settings.AddAccount(this.Account.Address, json); })); }
private bool LoadGameKey() { if (ReferenceEquals(GameKey, null)) { if (args.Contains("key")) { GameKey = args.Value <string>("key"); return(!ReferenceEquals(GameKey, null)); } else { // keystore file for node key string keystore = (string)config["game"]["keystore"]; if (string.IsNullOrEmpty(keystore)) { throw new Exception("keystore file not found"); } // password for master key string passphrase = args.Value("passphrase"); if (string.IsNullOrEmpty(passphrase)) { BConsole.WriteLine(Color.DarkYellow, "[INFO] ", "gamekey is locked! you should unlock first to start"); passphrase = BConsole.ReadPassword(Color.White, "passphrase: "); if (string.IsNullOrEmpty(passphrase)) { throw new KeyNotFoundException("passphrase for game key"); } } // game key Log.Write("unlocking game key"); var task = Task.Run(() => { GameKey = KeyStoreService.DecryptKeyStoreV3FromFile(keystore, passphrase); }); int tick = 0; while (!task.IsCompleted) { Thread.Sleep(10); if (tick != NetTime.UnixTime) { Log.Write("."); tick = NetTime.UnixTime; } } } bool res = !ReferenceEquals(GameKey, null); Log.Write(" [", res ? Color.DarkGreen : Color.DarkRed, res ? " OK " : "FAIL", "]"); Log.WriteLine(", coinbase=", Color.DarkGreen, GameKey.Address); } return(!ReferenceEquals(GameKey, null)); }
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 }
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)); }
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 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 string CreateAccount(string password) { //Generate a private key pair using SecureRandom var ecKey = Nethereum.Signer.EthECKey.GenerateKey(); var address = ecKey.GetPublicAddress(); var service = new KeyStoreService(); var encryptedKey = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), address); return(encryptedKey); }
public static string EncryptToJson(byte[] privateKey, string password) { byte[] publicKey = Secp256k1.DerivePublicKey(privateKey); string address = SimpleWallet.PublicKeyToAddress(publicKey); KeyStoreService keyStore = new KeyStoreService(); string jsonString = keyStore.EncryptAndGenerateDefaultKeyStoreAsJson(password, privateKey, address); JObject json = JObject.Parse(jsonString); json["address"] = json["address"].ToString().Replace("0x", ""); return(json.ToString()); }
private void OnCommandAccountsNew(string[] args) { string name = args.Length > 0 ? args[0] : BConsole.ReadLine("name: "); if (string.IsNullOrEmpty(name)) { return; } if (wallets.Contains(name)) { BConsole.WriteLine("account name already exists"); return; } string password = BConsole.ReadPassword("password: "******"confirm: "); if (password != confirm) { BConsole.WriteLine("password mismatch"); return; } string token = BConsole.ReadLine("token: "); if (string.IsNullOrEmpty(token)) { BConsole.WriteLine("key export token not found"); return; } Task.Run(async() => { (string key, string error) = await web4b.GetUserKeyAsync(token); if (string.IsNullOrEmpty(key)) { BConsole.WriteLine("error: ", error); return; } BConsole.WriteLine("key received! wait a while encrypting key..."); string keystore = KeyStoreService.EncryptKeyStoreV3(key, password); var account = wallets.Add(name, keystore); BConsole.WriteLine(name, "(", account.Address, ") imported!"); }); }
public void TestSetup() { if (!File.Exists(this.keystore_file)) { KeyStoreService.GenerateKeyStore(this.keystore_path, this.password, this.privatekey, this.base85_address, out keystore_file); } }
/// <summary> /// Set the account address according to the keyStore found /// </summary> /// <returns></returns> public bool RetrieveAddressFromKeystore() { if (keystoreJSON == null || keystoreJSON == "") { return(false); } KeyStoreService m_keystoreService = new KeyStoreService(); SetCurrentAddress(m_keystoreService.GetAddressFromKeyStore(keystoreJSON)); return(true); }
public void GenerateNewAccountFileFromPrivateKey(string pass, string path, string address, string key) { var service = new KeyStoreService(); var fileName = service.GenerateUTCFileName(address); using (var newfile = File.CreateText(Path.Combine(path, fileName))) { var newJson = service.EncryptAndGenerateDefaultKeyStoreAsJson(pass, HexByteConvertorExtensions.HexToByteArray(key), address); newfile.Write(newJson); newfile.Flush(); } }
#pragma warning restore IDE0044 // Add readonly modifier //Create new account, returns account address public string CreateNew(string path, string password) { Nethereum.Signer.EthECKey ecKey = Nethereum.Signer.EthECKey.GenerateKey(); string address = ecKey.GetPublicAddress(); KeyStoreService service = new KeyStoreService(); string encryptedKey = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), address); string filename = service.GenerateUTCFileName(address); SaveToKeystore(path, filename, encryptedKey); return(address); }
public void MakeKeyStoreFile() { if (File.Exists(this.keystore_file)) { File.Delete(this.keystore_file); } KeyStoreService.GenerateKeyStore(this.keystore_path, this.password, this.privatekey, this.base85_address, out _).Should().BeTrue(); }
static void Main(string[] args) { EthECKey ethECKey = EthECKey.GenerateKey(); byte[] key = ethECKey.GetPrivateKeyAsBytes(); var address = ethECKey.GetPublicAddress(); string password = "******"; var ksvc = new KeyStoreService(); string json = ksvc.EncryptAndGenerateDefaultKeyStoreAsJson(password, key, address); var ksfn = string.Format(@"e:\{0}.json", ksvc.GenerateUTCFileName(address)); File.WriteAllText(ksfn, json); }
public ContractDemo CreateAccount() { //To full the new account var password = "******"; var senderAddress = "0x12890d2cce102216644c59daE5baed380d84830c"; var web3 = new Nethereum.Web3.Web3(new ManagedAccount(senderAddress, password)); var transactionPolling = new TransactionReceiptPollingService(web3); string path = @"C:\Programathon\Nethereum-master\testchain\devChain\keystore\"; //Generate a private key pair using SecureRandom var ecKey = Nethereum.Signer.EthECKey.GenerateKey(); //Get the public address (derivied from the public key) var newAddress = ecKey.GetPublicAddress(); var privateKey = ecKey.GetPrivateKey(); //Create a store service, to encrypt and save the file using the web3 standard var service = new KeyStoreService(); var encryptedKey = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, ecKey.GetPrivateKeyAsBytes(), newAddress); var fileName = service.GenerateUTCFileName(newAddress); //save the File using (var newfile = System.IO.File.CreateText(Path.Combine(path, fileName))) { newfile.Write(encryptedKey); newfile.Flush(); } var web3Geth = new Web3Geth(); var miningResult = web3Geth.Miner.Start.SendRequestAsync(6).Result; var currentBalance = web3.Eth.GetBalance.SendRequestAsync(newAddress).Result; //when sending a transaction using an Account, a raw transaction is signed and send using the private key var transactionReceipt = transactionPolling.SendRequestAsync(() => web3.TransactionManager.SendTransactionAsync(senderAddress, newAddress, new HexBigInteger(4000000000000000000)) ).Result; var newBalance = web3.Eth.GetBalance.SendRequestAsync(newAddress).Result; miningResult = web3Geth.Miner.Stop.SendRequestAsync().Result; ContractDemo d = new ContractDemo(); d.Address = newAddress; return(d); }
public void GenerateNewAccountFile(string pass, string path) { var ecKey = EthECKey.GenerateKey(); byte[] privateKey = null; while (true) { privateKey = ecKey.GetPrivateKeyAsBytes(); if (privateKey.Length == 32) { break; } ecKey = EthECKey.GenerateKey(); } var genAddress = ecKey.GetPublicAddress(); var service = new KeyStoreService(); var fileName = service.GenerateUTCFileName(genAddress); //using (var newfile = File.CreateText(fileName)) //{ // //generate the encrypted and key store content as json. (The default uses pbkdf2) // var newJson = service.EncryptAndGenerateDefaultKeyStoreAsJson(password, privateKey, genAddress); // newfile.Write(newJson); // newfile.Flush(); //} //instead of the default service we can use either //Scrypt using (var newfile = File.CreateText(Path.Combine(path, fileName))) { //generate the encrypted and key store content as json. (The default uses pbkdf2) var scryptService = new KeyStoreScryptService(); var scryptResult = scryptService.EncryptAndGenerateKeyStoreAsJson(pass, privateKey, genAddress); newfile.Write(scryptResult); newfile.Flush(); } Process.Start(path); //or pkbdf2 //var pbkdf2Service = new KeyStorePbkdf2Service(); //var pkbdf2Result = pbkdf2Service.EncryptAndGenerateKeyStoreAsJson(password, privateKey, genAddress); //File.WriteAllText("UTC--" + DateTime.UtcNow.ToString("o", // CultureInfo.InvariantCulture).Replace(':', '-') + "--" + genAddress, scryptResult); //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 }
public void InstantiateWalletAndSaveOnDisk(String wordsChain, String password) { m_wallet = new Wallet(wordsChain, null); SetCurrentAddress(EthECKey.GetPublicAddress(ProviderManager.instance.m_wallet.GetWalletPrivateKeyAsString())); KeyStoreService m_keystoreService = new KeyStoreService(); Debug.Log(Application.persistentDataPath); string keystoreJSON = m_keystoreService.EncryptAndGenerateDefaultKeyStoreAsJson(password, ProviderManager.instance.m_wallet.GetWalletPrivateKeyAsByte(), accountAddress); SaveJSONOnDisk(keystoreJSON, Application.persistentDataPath + "/keystore.ks"); }
public void Init() { var dfsOptions = new DfsOptions(new BlockOptions(), new DiscoveryOptions(), new RepositoryOptions(FileSystem, Constants.DfsDataSubDir), Substitute.For <KeyChainOptions>(), Substitute.For <SwarmOptions>(), Substitute.For <IDnsClient>()); _keyStoreService = new KeyStoreService(dfsOptions) { Options = dfsOptions.KeyChain }; var securePassword = new SecureString(); "mypassword".ToList().ForEach(c => securePassword.AppendChar(c)); securePassword.MakeReadOnly(); _keyStoreService.SetPassphraseAsync(securePassword).ConfigureAwait(false); }