/// <summary>
        /// Converts the value of the current <see cref="CascadingSymmetricKey" /> to its equivalent binary representation.
        /// </summary>
        /// <returns>
        /// A binary representation of the current <see cref="CascadingSymmetricKey" />.
        /// </returns>
        public SecureBuffer ToBuffer()
        {
            var result = new SecureBuffer(SerializedLength);

            try
            {
                using (var controlToken = StateControl.Enter())
                {
                    result.Access(pinnedResultBuffer =>
                    {
                        var keyLength = SecureSymmetricKey.SerializedLength;

                        for (var i = 0; i < MaximumDepth; i++)
                        {
                            if (i < Depth)
                            {
                                using (var keyBuffer = Keys[i].ToBuffer())
                                {
                                    keyBuffer.Access(pinnedKeyBuffer =>
                                    {
                                        // Copy the key buffers out to the result buffer.
                                        Array.Copy(pinnedKeyBuffer, 0, pinnedResultBuffer, (keyLength * i), keyLength);
                                    });
                                }

                                continue;
                            }

                            // Fill the unused segments with random bytes.
                            var randomBytes = new Byte[keyLength];
                            HardenedRandomNumberGenerator.Instance.GetBytes(randomBytes);
                            Array.Copy(randomBytes, 0, pinnedResultBuffer, (keyLength * i), keyLength);
                        }

                        // Append the depth as a 16-bit integer.
                        Buffer.BlockCopy(BitConverter.GetBytes(Convert.ToUInt16(Depth)), 0, pinnedResultBuffer, (SerializedLength - sizeof(UInt16)), sizeof(UInt16));
                    });

                    return(result);
                }
            }
            catch
            {
                result.Dispose();
                throw new SecurityException("Key serialization failed.");
            }
        }
        /// <summary>
        /// Converts the value of the current <see cref="SecureSymmetricKey" /> to its equivalent binary representation.
        /// </summary>
        /// <returns>
        /// A binary representation of the current <see cref="SecureSymmetricKey" />.
        /// </returns>
        public SecureBuffer ToBuffer()
        {
            var resultBuffer = new SecureBuffer(SerializedLength);

            try
            {
                using (var controlToken = StateControl.Enter())
                {
                    using (var plaintextBuffer = new PinnedBuffer(SerializedPlaintextLength, true))
                    {
                        KeySource.Access(pinnedKeySourceBuffer =>
                        {
                            Array.Copy(pinnedKeySourceBuffer, 0, plaintextBuffer, KeySourceBufferIndex, KeySourceLengthInBytes);
                        });

                        plaintextBuffer[AlgorithmBufferIndex]      = (Byte)Algorithm;
                        plaintextBuffer[DerivationModeBufferIndex] = (Byte)DerivationMode;

                        using (var cipher = BufferEncryptionAlgorithm.ToCipher(RandomnessProvider))
                        {
                            using (var initializationVector = new PinnedBuffer(cipher.BlockSizeInBytes, true))
                            {
                                RandomnessProvider.GetBytes(initializationVector);

                                resultBuffer.Access(pinnedResultBuffer =>
                                {
                                    using (var ciphertext = cipher.Encrypt(plaintextBuffer, BufferEncryptionKey, initializationVector))
                                    {
                                        Array.Copy(ciphertext, 0, pinnedResultBuffer, 0, SerializedLength);
                                    }
                                });
                            }
                        }
                    }
                }

                return(resultBuffer);
            }
            catch
            {
                resultBuffer.Dispose();
                throw new SecurityException("Key serialization failed.");
            }
        }
Exemple #3
0
        private static void run(IConfigSectionNode args)
        {
            var pretty         = args["pp", "pretty"].Exists;
            var noEntropy      = args["ne", "noentropy"].Exists;
            var scoreThreshold = args["st", "score"].AttrByIndex(0).ValueAsInt(80);

            if (scoreThreshold < 20)
            {
                scoreThreshold = 20;
            }
            if (scoreThreshold > 100)
            {
                scoreThreshold = 100;
            }
            var strength = args["lvl", "level"].AttrByIndex(0).ValueAsEnum <PasswordStrengthLevel>(PasswordStrengthLevel.Default);

            ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Welcome.txt"));

            if (args["?", "h", "help"].Exists)
            {
                ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Help.txt"));
                return;
            }

            ConsoleUtils.Info("Score Threshold: {0}%".Args(scoreThreshold));
            ConsoleUtils.Info("Stength level: {0}".Args(strength));

            if (!noEntropy)
            {
                var count = ExternalRandomGenerator.Instance.NextScaledRandomInteger(47, 94);
                ConsoleUtils.Info("Acquiring entropy from user...");
                Console.WriteLine();
                ConsoleUtils.WriteMarkupContent(
                    @"<push>
<f color=magenta>Please make <f color=white>{0}<f color=magenta> random keystrokes
Do not hit the same key and try to space key presses in time:<pop>
".Args(count));

                var pnow = Stopwatch.GetTimestamp();

                Console.WriteLine();
                for (var i = 0; i < count; i++)
                {
                    var k = Console.ReadKey(true).KeyChar;
                    if (k < 0x20)
                    {
                        continue;
                    }
                    var now     = Stopwatch.GetTimestamp();
                    var elapsed = (int)(39621 * (k - 0x19) * (now - pnow));
                    pnow = now;
                    ExternalRandomGenerator.Instance.FeedExternalEntropySample(elapsed);
                    Console.Write("\r{0}  {1} characters to go ...", elapsed, count - i - 1);
                }
                ConsoleUtils.Info("OK. Entropy key entered");
                Console.WriteLine("-----------------------");
                System.Threading.Thread.Sleep(3000);
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);
                }
            }

            SecureBuffer password = null;

            while (true)
            {
                Console.WriteLine("Please type-in your password and press <enter>:");
                password = ConsoleUtils.ReadPasswordToSecureBuffer('*');
                var score = App.SecurityManager.PasswordManager.CalculateStrenghtPercent(PasswordFamily.Text, password);
                var pass  = score >= scoreThreshold;
                Console.WriteLine();
                var t = "Password score: {0}% is {1} strong".Args(score, pass ? "sufficiently" : "insufficiently");
                if (pass)
                {
                    ConsoleUtils.Info(t);
                    break;
                }

                ConsoleUtils.Error(t);
                Console.WriteLine();
            }

            Console.WriteLine();

            while (true)
            {
                Console.WriteLine("Please re-type your password and press <enter>:");
                using (var p2 = ConsoleUtils.ReadPasswordToSecureBuffer('*'))
                    if (password.Content.MemBufferEquals(p2.Content))
                    {
                        break;
                    }
                ConsoleUtils.Error("Passwords do not match");
            }

            Console.WriteLine();
            Console.WriteLine();

            var hashed = App.SecurityManager.PasswordManager.ComputeHash(
                NFX.Security.PasswordFamily.Text,
                password,
                strength);

            password.Dispose();

            var toPrint = JSONWriter.Write(hashed, pretty ? JSONWritingOptions.PrettyPrintASCII : JSONWritingOptions.CompactASCII);

            Console.WriteLine("Hashed Password:");
            Console.WriteLine();

            Console.WriteLine(toPrint);
        }
Exemple #4
0
        private static void doPassword(IApplication app, bool pretty, int scoreThreshold, PasswordStrengthLevel strength, string algname)
        {
            ConsoleUtils.Info("Score Threshold: {0}%".Args(scoreThreshold));
            ConsoleUtils.Info("Strength level: {0}".Args(strength));

            SecureBuffer password = null;

            while (true)
            {
                Console.WriteLine("Please type-in your password and press <enter>:");
                password = ConsoleUtils.ReadPasswordToSecureBuffer('*');
                var score = app.SecurityManager.PasswordManager.CalculateStrenghtPercent(PasswordFamily.Text, password);
                var pass  = score >= scoreThreshold;
                Console.WriteLine();
                var t = "Password score: {0}% is {1} strong".Args(score, pass ? "sufficiently" : "insufficiently");
                if (pass)
                {
                    ConsoleUtils.Info(t);
                    break;
                }

                ConsoleUtils.Error(t);
                Console.WriteLine();
            }

            Console.WriteLine();

            while (true)
            {
                Console.WriteLine("Please re-type your password and press <enter>:");
                using (var p2 = ConsoleUtils.ReadPasswordToSecureBuffer('*'))
                    if (password.Content.MemBufferEquals(p2.Content))
                    {
                        break;
                    }
                ConsoleUtils.Error("Passwords do not match");
            }

            Console.WriteLine();
            Console.WriteLine();

            HashedPassword hashed = null;

            if (algname.IsNotNullOrWhiteSpace())
            {
                var alg = app.SecurityManager.PasswordManager.Algorithms[algname];
                if (alg != null)
                {
                    hashed = alg.ComputeHash(PasswordFamily.Text, password);
                }
                else
                {
                    ConsoleUtils.Error("Specified algorithm not found. Using default...");
                }
            }

            if (hashed == null)
            {
                hashed = app.SecurityManager.PasswordManager.ComputeHash(
                    PasswordFamily.Text,
                    password,
                    strength);
            }

            password.Dispose();

            var toPrint = JsonWriter.Write(hashed, pretty ? JsonWritingOptions.PrettyPrintASCII : JsonWritingOptions.CompactASCII);

            Console.WriteLine("Hashed Password:");
            Console.WriteLine();

            Console.WriteLine(toPrint);
        }