コード例 #1
0
        public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, string password, int minGapLimit = AbsoluteMinGapLimit, string filePath = null, KeyPath accountKeyPath = null)
        {
            HdPubKeys               = new List <HdPubKey>();
            HdPubKeyScriptBytes     = new List <byte[]>();
            ScriptHdPubKeyMap       = new Dictionary <Script, HdPubKey>();
            HdPubKeysLock           = new object();
            HdPubKeyScriptBytesLock = new object();
            ScriptHdPubKeyMapLock   = new object();
            BlockchainState         = new BlockchainState();
            BlockchainStateLock     = new object();
            HardwareWalletInfo      = null;

            if (password is null)
            {
                password = "";
            }

            SetMinGapLimit(minGapLimit);

            EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret);
            ChainCode       = Guard.NotNull(nameof(chainCode), chainCode);
            var extKey = new ExtKey(encryptedSecret.GetKey(password), chainCode);

            MasterFingerprint = extKey.Neuter().PubKey.GetHDFingerPrint();
            AccountKeyPath    = accountKeyPath ?? DefaultAccountKeyPath;
            ExtPubKey         = extKey.Derive(AccountKeyPath).Neuter();

            SetFilePath(filePath);
            ToFileLock = new object();
            ToFile();
        }
コード例 #2
0
        static void Main(string[] args)
        {
            var walletPath = args[0];
            var password   = args[1];

            var encryptedSecret = string.Empty;
            var chainCode       = string.Empty;

            var lines = File.ReadAllLines(walletPath, Encoding.UTF8);

            foreach (var line in lines.Select(x => x.Trim()))
            {
                if (line.Contains("EncryptedSecret"))
                {
                    encryptedSecret = line.Split().Last();
                }
                if (line.Contains("ChainCode"))
                {
                    chainCode = line.Split().Last();
                }
            }

            encryptedSecret = encryptedSecret.Substring(1, encryptedSecret.Length - 3);
            chainCode       = chainCode.Substring(1, chainCode.Length - 3);

            var secret = new BitcoinEncryptedSecretNoEC(encryptedSecret, Network.Main);
            var ccode  = Encoders.Base64.DecodeData(chainCode);

            var extKey = new ExtKey(secret.GetKey(password), ccode);

            Console.WriteLine(extKey.GetWif(Network.Main));
        }
コード例 #3
0
        public static bool TryFind(Wallet wallet, string language, bool useNumbers, bool useSymbols, string likelyPassword, out string?foundPassword, Action <int, TimeSpan>?reportPercentage = null, CancellationToken cancellationToken = default)
        {
            foundPassword = null;
            BitcoinEncryptedSecretNoEC encryptedSecret = wallet.KeyManager.EncryptedSecret;

            var charset = Charsets[language] + (useNumbers ? "0123456789" : "") + (useSymbols ? "|!¡@$¿?_-\"#$/%&()´+*=[]{},;:.^`<>" : "");

            var attempts          = 0;
            var maxNumberAttempts = likelyPassword.Length * charset.Length;

            Stopwatch sw = Stopwatch.StartNew();

            foreach (var pwd in GeneratePasswords(likelyPassword, charset.ToArray()))
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    encryptedSecret.GetKey(pwd);
                    foundPassword = pwd;
                    return(true);
                }
                catch (SecurityException)
                {
                }

                attempts++;
                var percentage    = (int)((float)attempts / maxNumberAttempts * 100);
                var remainingTime = sw.Elapsed / percentage * (100 - percentage);

                reportPercentage?.Invoke(percentage, remainingTime);
            }

            return(false);
        }
コード例 #4
0
        // Function to convert a #seconds to something more legible
        //    @parm: strToTest
        //              This is the string that is currently under test
        //    @parm: enc
        //              Reference to the encryption object which contains
        //              the EncryptedSecret
        //    @parm: debug
        //              If this is enabled, print the result of the test to
        //              the STDOUT as well as to ofile

        static int TestPass(string strToTest,
                            ref BitcoinEncryptedSecretNoEC enc,
                            bool debug = true)
        {
            var sw = new Stopwatch();

            if (debug)
            {
                sw.Start();
                output("TEST [" + strToTest + "]");
            }
            try
            {
                enc.GetKey(strToTest);
                output("--KEY FOUND " + strToTest);
                return(0);
            }
            catch
            {
                if (debug)
                {
                    sw.Stop();

                    output("--FAIL (" + sw.Elapsed.Seconds.ToString() + "." + sw.Elapsed.Milliseconds.ToString() + ")");
                }
                return(-1);
            }
        }
コード例 #5
0
        public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, string password, string filePath = null)
        {
            HdPubKeys               = new List <HdPubKey>();
            HdPubKeyScriptBytes     = new List <byte[]>();
            ScriptHdPubkeyMap       = new Dictionary <Script, HdPubKey>();
            HdPubKeysLock           = new object();
            HdPubKeyScriptBytesLock = new object();
            ScriptHdPubkeyMapLock   = new object();
            BlockchainState         = new BlockchainState();
            BlockchainStateLock     = new object();

            if (password is null)
            {
                password = "";
            }

            EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret);
            ChainCode       = Guard.NotNull(nameof(chainCode), chainCode);
            var extKey = new ExtKey(encryptedSecret.GetKey(password), chainCode);

            ExtPubKey = extKey.Derive(AccountKeyPath).Neuter();

            SetFilePath(filePath);
            ToFileLock = new object();
            ToFile();
        }
コード例 #6
0
        internal static void Find(string secret, string language, bool useNumbers, bool useSymbols)
        {
            BitcoinEncryptedSecretNoEC encryptedSecret;

            try
            {
                encryptedSecret = new BitcoinEncryptedSecretNoEC(secret);
            }
            catch (FormatException)
            {
                Logging.Logger.LogCritical("ERROR: The encrypted secret is invalid. Make sure you copied correctly from your wallet file.");
                return;
            }

            Logging.Logger.LogWarning <PasswordFinder>($"WARNING: This tool will display your password if it finds it.");
            Logging.Logger.LogWarning <PasswordFinder>($"         You can cancel this by CTRL+C combination anytime." + Environment.NewLine);

            Console.Write("Enter a likely password: "******"0123456789" : "") + (useSymbols ? "|!¡@$¿?_-\"#$/%&()´+*=[]{},;:.^`<>" : "");

            var found             = false;
            var lastpwd           = string.Empty;
            var attempts          = 0;
            var maxNumberAttempts = password.Length * charset.Length;
            var stepSize          = (maxNumberAttempts + 101) / 100;

            Console.WriteLine();
            Console.Write($"[{string.Empty,100}] 0%");

            var sw = new Stopwatch();

            sw.Start();
            foreach (var pwd in GeneratePasswords(password, charset.ToArray()))
            {
                lastpwd = pwd;
                try
                {
                    encryptedSecret.GetKey(pwd);
                    found = true;
                    break;
                }
                catch (SecurityException)
                {
                }
                Progress(++attempts, stepSize, maxNumberAttempts, sw.Elapsed);
            }
            sw.Stop();

            Console.WriteLine();
            Console.WriteLine();
            Logging.Logger.LogInfo <PasswordFinder>($"Completed in {sw.Elapsed}");
            Console.WriteLine(found ? $"SUCCESS: Password found: >>> {lastpwd} <<<" : "FAILED: Password not found");
            Console.WriteLine();
        }
コード例 #7
0
        public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, string password)
        {
            HdPubKeys     = new List <HdPubKey>();
            HdPubKeysLock = new object();

            if (password == null)
            {
                password = "";
            }

            EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret);
            ChainCode       = Guard.NotNull(nameof(chainCode), chainCode);
            var extKey = new ExtKey(encryptedSecret.GetKey(password), chainCode);

            ExtPubKey = extKey.Derive(AccountKeyPath).Neuter();
        }
コード例 #8
0
        public void EncryptedSecretNoECmultiply()
        {
            var tests = new[]
            {
                new {
                    Passphrase  = "TestingOneTwoThree",
                    Encrypted   = "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg",
                    Unencrypted = "5KN7MzqK5wt2TP1fQCYyHBtDrXdJuXbUzm4A9rKAteGu3Qi5CVR",
                    Compressed  = false
                },
                new {
                    Passphrase  = "Satoshi",
                    Encrypted   = "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq",
                    Unencrypted = "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5",
                    Compressed  = false
                },
                new {
                    Passphrase  = "TestingOneTwoThree",
                    Encrypted   = "6PYNKZ1EAgYgmQfmNVamxyXVWHzK5s6DGhwP4J5o44cvXdoY7sRzhtpUeo",
                    Unencrypted = "L44B5gGEpqEDRS9vVPz7QT35jcBG2r3CZwSwQ4fCewXAhAhqGVpP",
                    Compressed  = true
                },
                new {
                    Passphrase  = "Satoshi",
                    Encrypted   = "6PYLtMnXvfG3oJde97zRyLYFZCYizPU5T3LwgdYJz1fRhh16bU7u6PPmY7",
                    Unencrypted = "KwYgW8gcxj1JWJXhPSu4Fqwzfhp5Yfi42mdYmMa4XqK7NJxXUSK7",
                    Compressed  = true
                }
            };

            //Slow test, run in parallel
            Parallel.ForEach(tests, test =>
            {
                var secret = new BitcoinSecret(test.Unencrypted, Network.Main);
                BitcoinEncryptedSecretNoEC encryptedKey = secret.PrivateKey.GetEncryptedBitcoinSecret(test.Passphrase, Network.Main);
                Assert.Equal(test.Encrypted, encryptedKey.ToString());

                Key actualSecret = encryptedKey.GetKey(test.Passphrase);
                Assert.Equal(test.Unencrypted, actualSecret.GetBitcoinSecret(Network.Main).ToString());

                Assert.Equal(test.Compressed, actualSecret.IsCompressed);
            });
        }
コード例 #9
0
        public HomeController(IConfiguration iConfig)
        {
            config = iConfig;
            var path        = config.GetValue <string>("PathKey");
            var keypass     = config.GetValue <string>("PassKey");
            Key _privateKey = null;

            if (System.IO.File.Exists(path))
            {
                var sec = new BitcoinEncryptedSecretNoEC(System.IO.File.ReadAllBytes(path), Network.TestNet);
                _privateKey = sec.GetKey(keypass);
            }
            else
            {
                _privateKey = new Key();
                var encKey = _privateKey.GetEncryptedBitcoinSecret(keypass, Network.TestNet);
                System.IO.File.WriteAllBytes(path, encKey.ToBytes());
            }
        }
コード例 #10
0
        public static bool TryFind(PasswordFinderOptions passwordFinderOptions, [NotNullWhen(true)] out string?foundPassword, Action <int, TimeSpan>?reportPercentage = null, CancellationToken cancellationToken = default)
        {
            foundPassword = null;
            BitcoinEncryptedSecretNoEC encryptedSecret = passwordFinderOptions.Wallet.KeyManager.EncryptedSecret;

            var charset = Charsets[passwordFinderOptions.Charset] + (passwordFinderOptions.UseNumbers ? "0123456789" : "") + (passwordFinderOptions.UseSymbols ? "|!¡@$¿?_-\"#$/%&()´+*=[]{},;:.^`<>" : "");

            var attempts          = 0;
            var likelyPassword    = passwordFinderOptions.LikelyPassword;
            var maxNumberAttempts = likelyPassword.Length * charset.Length;

            Stopwatch sw = Stopwatch.StartNew();

            foreach (var pwd in GeneratePasswords(likelyPassword, charset.ToArray()))
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    encryptedSecret.GetKey(pwd);
                    foundPassword = pwd;
                    return(true);
                }
                catch (SecurityException)
                {
                }

                attempts++;
                var percentage            = (double)attempts / maxNumberAttempts * 100;
                var remainingMilliseconds = sw.Elapsed.TotalMilliseconds / percentage * (100 - percentage);

                reportPercentage?.Invoke((int)percentage, TimeSpan.FromMilliseconds(remainingMilliseconds));
            }

            return(false);
        }
コード例 #11
0
        private static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Please provide exactly 2 arguments. Example: dotnet run \"6PYSeErf23ArQL7xXUWPKa3VBin6cuDaieSdABvVyTA51dS4Mxrtg1CpGN\" \"password\"");

                return;
            }

            var encryptedSecretString = args[0];
            var encryptedSecret       = new BitcoinEncryptedSecretNoEC(encryptedSecretString);
            var password = args[1];

            try
            {
                encryptedSecret.GetKey(password);

                Console.WriteLine("SUCCESS! Correct password!");
            }
            catch (SecurityException)
            {
                Console.WriteLine("Wrong password.");
            }
        }
コード例 #12
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxPassword.Text))
            {
                MessageBox.Show(this, "You must enter a password and a Bitcoin Secret or Encrypted Key.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (string.IsNullOrEmpty(textBoxEncrypted.Text) && string.IsNullOrEmpty(textBoxSecret.Text))
            {
                MessageBox.Show(this, "You must enter a Bitcoin Secret or Encrypted Key.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (string.IsNullOrEmpty(textBoxEncrypted.Text))
            {
                using (new HourGlass())
                {
                    _result = Util.Interpret(textBoxSecret.Text);
                }

                if (_result == null || !(_result is BitcoinSecret))
                {
                    MessageBox.Show(this, "Unrecognized or invalid key.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                using (new HourGlass())
                {
                    try
                    {
                        BitcoinSecret          secret    = _result as BitcoinSecret;
                        BitcoinEncryptedSecret encrypted = secret.Encrypt(textBoxPassword.Text);
                        textBoxEncrypted.Text = encrypted.ToString();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else if (string.IsNullOrEmpty(textBoxSecret.Text))
            {
                using (new HourGlass())
                {
                    _result = Util.Interpret(textBoxEncrypted.Text);
                }

                if (_result == null || !(_result is BitcoinEncryptedSecretNoEC))
                {
                    MessageBox.Show(this, "Unrecognized or invalid key.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                using (new HourGlass())
                {
                    try
                    {
                        BitcoinEncryptedSecretNoEC encEC = _result as BitcoinEncryptedSecretNoEC;
                        textBoxSecret.Text = encEC.GetKey(textBoxPassword.Text).GetBitcoinSecret(Network.TestNet).ToString();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, ex.Message, "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
コード例 #13
0
        private static double averageCharLength = 6.4375; //Make this automatic

        private static void Main(string[] args)
        {
            var language   = "en";
            var useNumbers = true;
            var useSymbols = true;
            var secret     = string.Empty;
            var help       = false;
            var mode       = "allchars";

            var options = new OptionSet () {
                { "s|secret=", "The secret from your .json file (EncryptedSecret).",
                    v => secret = v },
                { "l|language=", "The charset to use: en, es, it, fr, pt. Default=en.",
                    v => language = v },
                { "n|numbers=", "Try passwords with numbers. Default=true.",
                    v => useNumbers = (v=="" || v=="1" || v.ToUpper()=="TRUE") },
                { "x|symbols=", "Try passwords with symbolds. Default=true.",
                    v => useSymbols = (v=="" || v=="1" || v.ToUpper()=="TRUE") },
                { "h|help", "Show Help",
                    v => help = true},
                { "m|mode", "set mode e.g. allchars, shiftError,",
                    v => mode = v }};

            options.Parse(args);
            if (help || string.IsNullOrEmpty(secret) || !Charsets.ContainsKey(language))
            {
                ShowHelp(options);
                return;
            }

            BitcoinEncryptedSecretNoEC encryptedSecret;
            try
            {
                encryptedSecret = new BitcoinEncryptedSecretNoEC(secret);
            }
            catch(FormatException)
            {
                Console.WriteLine("ERROR: The encrypted secret is invalid. Make sure you copied correctly from your wallet file.");
                return;
            }
            Console.WriteLine("Confirming this is Frank's version");
            Console.WriteLine($"WARNING: This tool will display you password if it finds it. Also, the process status display your wong password chars.");
            Console.WriteLine($"         You can cancel this by CTRL+C combination anytime." + Environment.NewLine);

            Console.Write("Enter password: "******"0123456789" : "") + (useSymbols ? "!@$?_-\"#$/%&()`+*[],;:.^<>" : "");

            var found = false;
            var lastpwd = string.Empty;
            var attempts = 0;
            var maxNumberAttempts = Convert.ToInt32(password.Length * averageCharLength * (password.Length-1) * averageCharLength * (password.Length-2) * averageCharLength);
            var stepSize = (maxNumberAttempts + 101) / 100;


            Console.WriteLine();
            Console.Write($"[{string.Empty, 100}] 0%");

            var sw = new Stopwatch();
            sw.Start();
            foreach(var pwd in GeneratePasswords(password))
            {
                lastpwd = pwd;
                try
                {
                    encryptedSecret.GetKey(pwd);
                    found = true; 
                    break;
                }
                catch (SecurityException)
                {
                }
                Progress(++attempts, stepSize, maxNumberAttempts, sw.Elapsed);
            }
            sw.Stop();

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine($"Completed in {sw.Elapsed}");
            Console.WriteLine(found ? $"SUCCESS: Password found: >>> {lastpwd} <<<" : "FAILED: Password not found");
            Console.WriteLine();
        }
コード例 #14
0
        private void buttonOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxKey.Text))
            {
                MessageBox.Show(this, "Enter a key.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            using (new HourGlass())
            {
                Result = Util.InterpretKey(textBoxKey.Text);
            }

            if (Result == null)
            {
                MessageBox.Show(this, "Unrecognized or invalid key.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                using (new HourGlass())
                {
                    Type type = Result.GetType();
                    switch (type.ToString())
                    {
                    case "NBitcoin.BitcoinEncryptedSecretEC":
                        if (string.IsNullOrEmpty(textBoxPassword.Text))
                        {
                            MessageBox.Show(this, "This is an encrypted BitcoinSecret, please provide the password.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                        else
                        {
                            try
                            {
                                BitcoinEncryptedSecretEC encEC = Result as BitcoinEncryptedSecretEC;
                                Result       = encEC.GetKey(textBoxPassword.Text).GetBitcoinSecret(Network.TestNet);
                                DialogResult = System.Windows.Forms.DialogResult.OK;
                            }
                            catch
                            {
                                MessageBox.Show(this, "The pasword you entered is incorrect.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;

                    case "NBitcoin.BitcoinEncryptedSecretNoEC":
                        if (string.IsNullOrEmpty(textBoxPassword.Text))
                        {
                            MessageBox.Show(this, "This is an encrypted BitcoinSecret, please provide the password.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                        else
                        {
                            try
                            {
                                BitcoinEncryptedSecretNoEC encEC = Result as BitcoinEncryptedSecretNoEC;
                                Result       = encEC.GetKey(textBoxPassword.Text).GetBitcoinSecret(Network.TestNet);
                                DialogResult = System.Windows.Forms.DialogResult.OK;
                            }
                            catch
                            {
                                MessageBox.Show(this, "The pasword you entered is incorrect.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;

                    case "NBitcoin.BitcoinPassphraseCode":
                        if (string.IsNullOrEmpty(textBoxPassword.Text))
                        {
                            MessageBox.Show(this, "This is a PassphraseCode, please provide the password.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                        else
                        {
                            try
                            {
                                BitcoinPassphraseCode phrase = Result as BitcoinPassphraseCode;
                                EncryptedKeyResult    key    = phrase.GenerateEncryptedSecret();

                                if (key.ConfirmationCode.Check(textBoxPassword.Text, key.GeneratedAddress))
                                {
                                    BitcoinSecret secret = key.EncryptedKey.GetSecret(textBoxPassword.Text);
                                    if (secret.GetAddress() == key.GeneratedAddress)
                                    {
                                        Result       = secret;
                                        DialogResult = System.Windows.Forms.DialogResult.OK;
                                    }
                                    else
                                    {
                                        MessageBox.Show(this, "The Generated Addresses do not match.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show(this, "The Confirmation Code check failed.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            catch
                            {
                                MessageBox.Show(this, "The password you entered is incorrect.", "Knoledge-keychain", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;

                    default:
                        DialogResult = System.Windows.Forms.DialogResult.OK;
                        break;
                    }
                }
            }
        }