コード例 #1
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();
        }
コード例 #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 KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, HDFingerprint?masterFingerprint, ExtPubKey extPubKey, bool?passwordVerified, int?minGapLimit, BlockchainState blockchainState, 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();
            BlockchainStateLock     = new object();

            EncryptedSecret   = encryptedSecret;
            ChainCode         = chainCode;
            MasterFingerprint = masterFingerprint;
            ExtPubKey         = Guard.NotNull(nameof(extPubKey), extPubKey);

            PasswordVerified = passwordVerified;
            SetMinGapLimit(minGapLimit);

            BlockchainState    = blockchainState ?? new BlockchainState();
            HardwareWalletInfo = null;
            AccountKeyPath     = accountKeyPath ?? DefaultAccountKeyPath;

            SetFilePath(filePath);
            ToFileLock = new object();
            ToFile();
        }
コード例 #4
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();
        }
コード例 #5
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);
            }
        }
コード例 #6
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);
        }
コード例 #7
0
        public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, ExtPubKey extPubKey)
        {
            HdPubKeys     = new List <HdPubKey>();
            HdPubKeysLock = new object();

            EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret);
            ChainCode       = Guard.NotNull(nameof(chainCode), chainCode);
            ExtPubKey       = Guard.NotNull(nameof(extPubKey), extPubKey);
        }
コード例 #8
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();
        }
コード例 #9
0
        // Function to test all possible single character mistypes
        //   @parm: password
        //            This is the password as you think it was typed..
        //   @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
        private static int TestSingleCharError(string password, ref BitcoinEncryptedSecretNoEC enc, bool debug)
        {
            char[] chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_- \"#$%&()=".ToArray();

            int max = password.Length * chars.Length;

            output("Total tests to perform: " + max);
            int count   = 0;
            int seconds = max / 2;

            output("Estimated time to completion: " + getTime(seconds));

            // The number of iterations that we'll use to average out how many
            // attempts per second (for time to complete estimate)
            int iter_average = 5;

            var sw = new Stopwatch();

            sw.Start();
            var pwChar = password.ToCharArray();

            for (int i = 0; i < password.Length; i++)
            {
                var original = pwChar[i];
                if (debug)
                {
                    output("Testing position " + i);
                }
                foreach (var c in chars)
                {
                    pwChar[i] = c;
                    string s = new string(pwChar);
                    if (TestPass(s, ref enc, debug) == 0)
                    {
                        output("Key Found " + s);
                        return(0);
                    }
                    count++;
                    if (count % iter_average == 0)
                    {
                        TimeSpan time     = sw.Elapsed;
                        decimal  rate     = (decimal)time.Seconds / (decimal)iter_average;
                        decimal  timeleft = (decimal)(max - count) * rate;
                        seconds = (int)timeleft;
                        sw.Restart();

                        if (debug)
                        {
                            output("-Estimated Time to completion: " + getTime(seconds));
                        }
                    }
                }
                pwChar[i] = original;
            }
            return(-1);
        }
コード例 #10
0
ファイル: KeyManager.cs プロジェクト: plazma48/WalletWasabi
        public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, ExtPubKey extPubKey, string filePath = null)
        {
            HdPubKeys     = new List <HdPubKey>();
            HdPubKeysLock = new object();

            EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret);
            ChainCode       = Guard.NotNull(nameof(chainCode), chainCode);
            ExtPubKey       = Guard.NotNull(nameof(extPubKey), extPubKey);
            SetFilePath(filePath);
            ToFileLock = new object();
            ToFile();
        }
コード例 #11
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();
        }
コード例 #12
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());
            }
        }
コード例 #13
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);
            });
        }
コード例 #14
0
        private static void Main(string[] args)
        {
            parameters.tests = new List <string> ();
            try
            {
                parms.Parse(args);
                if (parameters.help)
                {
                    ShowHelp(parms);
                    return;
                }
                BitcoinEncryptedSecretNoEC encryptedSecret = new BitcoinEncryptedSecretNoEC(parameters.secret);

                for (int i = 0; i < parameters.tests.Count; ++i)
                {
                    string t = parameters.tests[i];
                    switch (t)
                    {
                    case "shift_test":
                        TestShiftError(parameters.password, ref encryptedSecret, parameters.debug);
                        break;

                    case "single_char_test":
                        TestSingleCharError(parameters.password, ref encryptedSecret, parameters.debug);
                        break;

                    default:
                        Console.WriteLine("Unknown test type (" + t + ")");
                        break;
                    }
                }
            }
            catch (OptionException e) {
                Console.WriteLine("Exception Thrown");
                Console.WriteLine(e.Message);
                ShowHelp(parms);
                return;
            }
        }
コード例 #15
0
        public KeyManager(BitcoinEncryptedSecretNoEC encryptedSecret, byte[] chainCode, ExtPubKey extPubKey, bool?passwordVerified, BlockchainState blockchainState, 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();
            BlockchainStateLock     = new object();

            EncryptedSecret = Guard.NotNull(nameof(encryptedSecret), encryptedSecret);
            ChainCode       = Guard.NotNull(nameof(chainCode), chainCode);
            ExtPubKey       = Guard.NotNull(nameof(extPubKey), extPubKey);

            PasswordVerified = passwordVerified;

            BlockchainState = blockchainState ?? new BlockchainState();

            SetFilePath(filePath);
            ToFileLock = new object();
            ToFile();
        }
コード例 #16
0
        public static bool TryGetEncryptedSecretFromFile(string filePath, out BitcoinEncryptedSecretNoEC encryptedSecret)
        {
            encryptedSecret = default;
            filePath        = Guard.NotNullOrEmptyOrWhitespace(nameof(filePath), filePath);

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"Wallet file not found at: `{filePath}`.");
            }

            // Example text to handle: "ExtPubKey": "03BF8271268000000013B9013C881FE456DDF524764F6322F611B03CF6".
            var encryptedSecretLine = File.ReadLines(filePath) // Enumerated read.
                                      .Take(21)                // Limit reads to x lines.
                                      .FirstOrDefault(line => line.Contains("\"EncryptedSecret\": \"", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(encryptedSecretLine))
            {
                return(false);
            }

            var parts = encryptedSecretLine.Split("\"EncryptedSecret\": \"");

            if (parts.Length != 2)
            {
                throw new FormatException($"Could not split line: {encryptedSecretLine}");
            }

            var encsec = parts[1].TrimEnd(',', '"');

            if (string.IsNullOrEmpty(encsec) || encsec.Equals("null", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            encryptedSecret = new BitcoinEncryptedSecretNoEC(encsec);
            return(true);
        }
コード例 #17
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.");
            }
        }
コード例 #18
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);
        }
コード例 #19
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;
                    }
                }
            }
        }
コード例 #20
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();
        }
コード例 #21
0
        // Function to test all possible shift combinations of a password
        //   @parm: password
        //            This is the password as you think it was typed..
        //   @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 void TestShiftError(string password,
                                   ref BitcoinEncryptedSecretNoEC enc,
                                   bool debug = true)
        {
            int n = password.Length;

            // Number of permutations is 2^n
            int max = 1 << n;

            // We will track the number of combinations we've actually
            // performed for time to complete estimate
            int count = 0;

            // Track the number of seconds left to completion (Estimate)
            // We initially estimate 0.5s per test, this will get updated later once
            // we've begun running tests
            int seconds = max / 2;

            output("Max combinations " + max.ToString());

            output("-Estimated Time to Completion: " + getTime(seconds));

            // The number of iterations that we'll use to average out how many
            // attempts per second (for time to complete estimate)
            int iter_average = 5;

            // Converting string
            // to lower case
            password = password.ToLower();

            // We use a stopwatch to estimate how long this test will take to run
            var sw = new Stopwatch();

            sw.Start();

            // Using all subsequences
            // and permuting them
            for (int i = 0; i < max; i++)
            {
                char [] combination = password.ToCharArray();

                // If j-th bit is set, we
                // convert it to upper case
                for (int j = 0; j < n; j++)
                {
                    if (((i >> j) & 1) == 1)
                    {
                        switch (combination[j])
                        {
                        case '1':
                            combination[j] = '!';
                            break;

                        case '2':
                            combination[j] = '@';
                            break;

                        case '3':
                            combination[j] = '#';
                            break;

                        case '4':
                            combination[j] = '$';
                            break;

                        case '5':
                            combination[j] = '%';
                            break;

                        case '6':
                            combination[j] = '^';
                            break;

                        case '7':
                            combination[j] = '&';
                            break;

                        case '8':
                            combination[j] = '*';
                            break;

                        case '9':
                            combination[j] = '(';
                            break;

                        case '0':
                            combination[j] = ')';
                            break;

                        case '[':
                            combination[j] = '{';
                            break;

                        case ']':
                            combination[j] = '}';
                            break;

                        case ';':
                            combination[j] = ':';
                            break;

                        case '\'':
                            combination[j] = '"';
                            break;

                        // handles all a-z characters
                        default:
                            combination[j] = (char)(combination[j] - 32);
                            break;
                        }

                        // Printing current combination
                        string s = new string(combination);
                        if (TestPass(s, ref enc, debug) == 0)
                        {
                            output("Key Found " + s);
                            return;
                        }
                        count++;


                        if (count % iter_average == 0)
                        {
                            TimeSpan time     = sw.Elapsed;
                            decimal  rate     = (decimal)time.Seconds / (decimal)iter_average;
                            decimal  timeleft = (decimal)(max - count) * rate;
                            seconds = (int)timeleft;
                            sw.Restart();

                            if (debug)
                            {
                                output("-Estimated Time to completion: " + getTime(seconds));
                            }
                        }
                    }
                }
            }
        }
コード例 #22
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);
                    }
                }
            }
        }