コード例 #1
0
        private async Task UpdatePasswordStrengthIndicator(string newValue)
        {
            await Task.Yield();

            string password = (string)newValue;

            if (!String.IsNullOrEmpty(password))
            {
                bool isWeak = Dictionaries.Instance.IsKnownWeak(password);
                if (isWeak)
                {
                    _strengthCheck = StrengthCheckResult.InWeakDictionary;
                    StrengthIndicatorBackgroundColour = Color.Red;
                }
                else
                {
                    double strength = SimpleRandomGenerator.GetStrength(password);
                    _strengthCheck = strength >= _threshold ? StrengthCheckResult.OK : StrengthCheckResult.FailComplexityCheck;
                    StrengthIndicatorBackgroundColour = _strengthCheck == StrengthCheckResult.OK ? Color.Green : Color.Orange;
                }
            }
            else
            {
                _strengthCheck = StrengthCheckResult.None;
                StrengthIndicatorBackgroundColour = Color.Gray;
            }
            OnPropertyChanged("StrengthIndicatorColWidth");
            OnPropertyChanged("StrengthIndicatorText");
            OnPropertyChanged("TextIsSet");
        }
コード例 #2
0
ファイル: VaultViewModel.cs プロジェクト: devoctomy/cachy
        public async void ClipboardFieldCopyCommandAction(Object parameter)
        {
            App.AppLogger.Logger.Log(devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.Information, "Clipboard field copy command invoked.");

            ResetIdleTime();
            ClipboardField field = parameter as ClipboardField;

            if (field != null)
            {
                try
                {
                    if (AppConfig.Instance.EnableClipboardObfuscator)
                    {
                        App.StopClipboardObfuscator(true, new TimeSpan(0, 0, 30));
                        await ClipboardObfuscator.Instance.PerformObfuscation(SimpleRandomGenerator.QuickGetRandomInt(1, 10));
                    }
                    await Xamarin.Essentials.Clipboard.SetTextAsync(field.Value);

                    App.AppLogger.Logger.Log(devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.Sensitive,
                                             "Successfully copied field to clipboard.");
                }
                catch (Exception ex)
                {
                    App.AppLogger.Logger.Log(devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.VerboseLow | devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.Exception,
                                             "Failed to set clipboard text.\r\n'{0}'.",
                                             ex.ToString());
                }
            }
        }
コード例 #3
0
ファイル: GraphBuilderTests.cs プロジェクト: devoctomy/cachy
        public void DeriveKeyNodeTest()
        {
            Byte[] salt = SimpleRandomGenerator.QuickGetRandomBytes(16);
            Rfc2898DeriveBytesNode node = new Rfc2898DeriveBytesNode(new GraphIO <String>(String.Empty), new GraphIO <Int32>(32), new GraphIO <Byte[]>(salt), new GraphIO <Int32>(10000));

            Byte[] key1   = null;
            Byte[] key2   = null;
            Object output = null;

            if (GraphBuilder.ExecuteIsolatedNode(node, node.Password, node.DervivedKey, "This is my passphrase!", out output))
            {
                key1 = (Byte[])output;
                if (GraphBuilder.ExecuteIsolatedNode(node, node.Password, node.DervivedKey, "This is my passphrase!", out output))
                {
                    key2 = (Byte[])output;
                    Assert.IsTrue(key1.SequenceEqual(key2));
                }
                else
                {
                    Assert.Fail();
                }
            }
            else
            {
                Assert.Fail();
            }
        }
コード例 #4
0
 private void add_process_Click(object sender, EventArgs e)
 {
     try
     {
         if (!String.IsNullOrWhiteSpace(processName_Text.Text) && !String.IsNullOrWhiteSpace(processID_Text.Text))
         {
             sjf.AddProcess(new ProcessDomain
             {
                 ProcessName    = processName_Text.Text,
                 ProcessID      = int.Parse(processID_Text.Text),
                 CompletionTime = SimpleRandomGenerator.GetRendomTime(),
                 Burst_Time     = SimpleRandomGenerator.GetRendomTime(),
                 ArrivalTime    = SimpleRandomGenerator.GetRendomTime(),
                 Priority       = ProcessPriority.Normal,
                 State          = ProcessState.New
             });
             processName_Text.Clear();
             processID_Text.Clear();
         }
         else
         {
             MessageBox.Show("Some input in textbox wrong");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
コード例 #5
0
 public void Start()
 {
     if (!_running)
     {
         Device.StartTimer(TimeSpan.FromMilliseconds(SimpleRandomGenerator.QuickGetRandomInt(2000, 30000)), TimerCallback);
         _stop    = false;
         _running = true;
     }
 }
コード例 #6
0
        public PasswordEntryView()
        {
            _showCommand = new Command(new Action <object>(ShowCommandAction));
            int recommendedCharSelection = SimpleRandomGenerator.GetTotalCharCountForSelection(SimpleRandomGenerator.CharSelection.Lowercase |
                                                                                               SimpleRandomGenerator.CharSelection.Uppercase |
                                                                                               SimpleRandomGenerator.CharSelection.Digits |
                                                                                               SimpleRandomGenerator.CharSelection.Minus |
                                                                                               SimpleRandomGenerator.CharSelection.Underline);

            _threshold = Math.Pow(12, recommendedCharSelection);
            InitializeComponent();
        }
コード例 #7
0
        private double Harness(ICacheManager cm, int TaskCount, int MaxItems, int GetCount)
        {
            var srg = new SimpleRandomGenerator();

            for (var i = 0; i < MaxItems; i++)
            {
                var f = new Foo();

                f.Name   = srg.Generate(new RandomGeneratorSetting(RandomCodeType.Alpha, 300));
                f.Size   = SafeClrConvert.ToInt32(new RandomGeneratorSetting(RandomCodeType.Num, 3));
                f.Price  = SafeClrConvert.ToInt32(new RandomGeneratorSetting(RandomCodeType.Num, 5));
                f.Exists = SafeClrConvert.ToInt32(new RandomGeneratorSetting(RandomCodeType.Num, 2)) % 2 == 0;

                cm.Add("item" + i, f);
            }

            var tasks = new Task[TaskCount];
            var rnd   = new Random();

            for (var i = 0; i < TaskCount; i++)
            {
                tasks[i] = new Task((c) =>
                {
                    var _c = c as ICacheManager;

                    if (_c != null)
                    {
                        for (var j = 0; j < GetCount; j++)
                        {
                            var x = _c.Get("item" + rnd.Next(0, MaxItems));

                            consume(x);

                            Thread.Yield();
                        }
                    }
                }, cm);
            }
            var sw = new Stopwatch();

            sw.Start();
            for (var i = 0; i < TaskCount; i++)
            {
                tasks[i].Start();
            }

            Task.WaitAll(tasks);
            sw.Stop();

            return(sw.ElapsedMilliseconds);
        }
コード例 #8
0
ファイル: GraphBuilderTests.cs プロジェクト: devoctomy/cachy
        public void AESEncryptEncodeDecodeDecryptNodeTest()
        {
            Byte[] salt      = SimpleRandomGenerator.QuickGetRandomBytes(16);
            String password  = "******";
            String plainText = "Testing testing, 123.";

            GraphBuilder           encryptGraph         = new GraphBuilder();
            GraphIO <String>       passwordInput        = new GraphIO <String>(plainText);
            GraphIO <Int32>        keyLengthInput       = new GraphIO <Int32>(32);
            GraphIO <Byte[]>       saltInput            = new GraphIO <Byte[]>(salt);
            Rfc2898DeriveBytesNode deriveEncryptKeyNode = new Rfc2898DeriveBytesNode(passwordInput, keyLengthInput, saltInput, new GraphIO <Int32>(10000));
            AESEncryptNode         encryptNode          = new AESEncryptNode(new GraphIO <String>(plainText), new GraphIO <Byte[]>(null), deriveEncryptKeyNode.DervivedKey);
            Base64EncodeNode       encodeNode           = new Base64EncodeNode(encryptNode.EncryptedData);

            encryptGraph.AddNode("deriveNode", deriveEncryptKeyNode);
            encryptGraph.AddNode("encryptNode", encryptNode);
            encryptGraph.AddNode("encodeNode", encodeNode);
            encryptGraph.CreateRoute("encrypt",
                                     deriveEncryptKeyNode.Password,
                                     encodeNode.EncodedData,
                                     "deriveNode",
                                     new String[] { "deriveNode", "encryptNode", "encodeNode" });

            Object output = null;

            if (encryptGraph.Process(true, "encrypt", password, out output))
            {
                String encryptedEncoded = (String)output;

                GraphBuilder           decryptGraph          = new GraphBuilder();
                GraphIO <String>       encryptedEncodedInput = new GraphIO <String>(encryptedEncoded);
                Rfc2898DeriveBytesNode deriveDecryptKeyNode  = new Rfc2898DeriveBytesNode(new GraphIO <String>(String.Empty), new GraphIO <Int32>(32), new GraphIO <Byte[]>(salt), new GraphIO <Int32>(10000));
                Base64DecodeNode       decodeNode            = new Base64DecodeNode(encryptedEncodedInput);
                AESDecryptNode         decryptNode           = new AESDecryptNode(decodeNode.UnencodedData, new GraphIO <Byte[]>(null), deriveDecryptKeyNode.DervivedKey);

                decryptGraph.AddNode("deriveNode", deriveDecryptKeyNode);
                decryptGraph.AddNode("decodeNode", decodeNode);
                decryptGraph.AddNode("decryptNode", decryptNode);
                decryptGraph.CreateRoute("decrypt",
                                         deriveDecryptKeyNode.Password,
                                         decryptNode.UnencryptedData,
                                         "deriveNode",
                                         new String[] { "deriveNode", "decodeNode", "decryptNode" });

                if (decryptGraph.Process(true, "decrypt", password, out output))
                {
                    String decodedDecrypted = (String)output;
                    Assert.IsTrue(decodedDecrypted == plainText);
                }
            }
        }
コード例 #9
0
        private async Task PerformObfuscation()
        {
            await Task.Yield();

            //generate a fake username or password here
            List <string> _fakes = new List <string>();

            if (FakeUsernames)
            {
                _logger.Log(LoggerMessageType.VerboseHigh | LoggerMessageType.Information, "Generating fake username.");
                string user = SimpleRandomGenerator.QuickGetRandomString(
                    SimpleRandomGenerator.CharSelection.Lowercase | SimpleRandomGenerator.CharSelection.Uppercase | SimpleRandomGenerator.CharSelection.Digits,
                    SimpleRandomGenerator.QuickGetRandomInt(4, 12),
                    false);
                string userName = String.Empty;
                if (_domains == null)
                {
                    _logger.Log(LoggerMessageType.VerboseHigh | LoggerMessageType.Information, "Loading list of domains for first time.");
                    _domains = new List <string>();
                    using (StringReader stringReader = new StringReader(Properties.Resources.domains))
                    {
                        string curLine = stringReader.ReadLine();
                        while (!String.IsNullOrEmpty(curLine))
                        {
                            if (!_domains.Contains(curLine))
                            {
                                _domains.Add(curLine);
                            }
                            curLine = stringReader.ReadLine();
                        }
                    }
                }
                string domain = SimpleRandomGenerator.QuickGetRandomStringArrayEntry(_domains.ToArray());
                userName = String.Format("{0}@{1}", user, domain);
                _fakes.Add(userName);
            }

            if (FakePasswords)
            {
                _logger.Log(LoggerMessageType.VerboseHigh | LoggerMessageType.Information, "Generating fake password.");
                _fakes.Add(SimpleRandomGenerator.QuickGetRandomString(SimpleRandomGenerator.CharSelection.All, 16, false));
            }

            _logger.Log(LoggerMessageType.VerboseHigh | LoggerMessageType.Information, "Randomly picking fake data.");
            string fakeEntry = SimpleRandomGenerator.QuickGetRandomStringArrayEntry(_fakes.ToArray());

            _logger.Log(LoggerMessageType.VerboseHigh | LoggerMessageType.Information, "Fake data picked, invoking obfuscate action.");
            await _action.Invoke(new ClipboardObfuscatorGeneratedFakeEventArgs(fakeEntry));
        }
コード例 #10
0
        public static bool IsWeak(this Credential credential)
        {
            if (_weakThreshold == -1)
            {
                int recommendedCharSelection = SimpleRandomGenerator.GetTotalCharCountForSelection(SimpleRandomGenerator.CharSelection.Lowercase |
                                                                                                   SimpleRandomGenerator.CharSelection.Uppercase |
                                                                                                   SimpleRandomGenerator.CharSelection.Digits |
                                                                                                   SimpleRandomGenerator.CharSelection.Minus |
                                                                                                   SimpleRandomGenerator.CharSelection.Underline);
                _weakThreshold = Math.Pow(12, recommendedCharSelection);
            }
            double strength = SimpleRandomGenerator.GetStrength(credential.Password);

            return(strength < _weakThreshold);
        }
コード例 #11
0
ファイル: AESUtilityTest.cs プロジェクト: devoctomy/cachy
        public void EncryptDecryptSimpleStringTest()
        {
            string plainText = "Hello World!";

            byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);

            byte[] iv  = SimpleRandomGenerator.QuickGetRandomBytes(16);
            byte[] key = SimpleRandomGenerator.QuickGetRandomBytes(32);

            byte[] cipherBytes = AESUtility.EncryptBytes(plainBytes, key, iv);

            byte[] decryptedBytes     = AESUtility.DecryptBytes(cipherBytes, key, iv);
            string decryptedPlainText = System.Text.Encoding.UTF8.GetString(decryptedBytes);

            Assert.AreEqual(plainText, decryptedPlainText);
        }
コード例 #12
0
        public override void Test()
        {
            var srg  = new SimpleRandomGenerator();
            var rgs  = new RandomGeneratorSetting(RandomCodeType.AlphaNum, 8);
            var data = new List <string>();

            for (var i = 0; i < 20; i++)
            {
                var x = srg.Generate(rgs);
                data.Add(x);
            }

            foreach (var code in data)
            {
                System.Console.WriteLine(code);
            }
        }
コード例 #13
0
ファイル: AuditLogEntryTests.cs プロジェクト: devoctomy/cachy
        public static AuditLogEntry CreateRandomAuditLogEntry(Random rng,
                                                              out String name,
                                                              out String type,
                                                              out AuditLogEntry.EntryType entryType)
        {
            name      = SimpleRandomGenerator.QuickGetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 6);
            type      = rng.Next(0, 100) >= 50 ? "vault" : "credential";
            entryType = SimpleRandomGenerator.QuickGetRandomEnum <AuditLogEntry.EntryType>(1, AuditLogEntry.EntryType.None);
            Dictionary <String, String> parameters = new Dictionary <String, String>();

            parameters.Add("Name", name);
            parameters.Add("Type", type);

            AuditLogEntry entry = new AuditLogEntry(entryType,
                                                    parameters.ToArray());

            return(entry);
        }
コード例 #14
0
ファイル: VaultViewModel.cs プロジェクト: devoctomy/cachy
        public async Task ExportCSV(object parameter)
        {
            App.AppLogger.Logger.Log(devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.Information, "Export CSV.");

            VaultExporter exporter = new VaultExporter(
                Common.ExportFormat.cachyCSV1_0,
                Common.ExportWrapping.PasswordProtectedZip);

            string extension = exporter.ExportWrapping == Common.ExportWrapping.PasswordProtectedZip ? "zip" : "csv";
            string name      = String.Format("{0}_{1}", Vault.Name, DateTime.Now.ToString("ddMMyyyy"));
            string fileName  = String.Format("{0}.{1}", name, extension);

            string passsword = SimpleRandomGenerator.QuickGetRandomString(
                SimpleRandomGenerator.CharSelection.All,
                16,
                true);

            byte[] exportData = exporter.Export(
                Vault,
                new KeyValuePair <string, string>("password", passsword));   //auto generate the password and display it in a popup after

            String fullExportPath = String.Empty;
            bool   success        = false;

            try
            {
                switch (Device.RuntimePlatform)
                {
                case Device.UWP:
                {
                    KeyValuePair <string, string[]> extensions = new KeyValuePair <string, string[]>(extension.ToUpper(), new string[] { String.Format(".{0}", extension) });
                    KeyValuePair <string, Stream>?  output     = await devoctomy.cachy.Framework.Native.Native.FileHandler.PickFileForSave(
                        fileName,
                        extensions);

                    if (output.HasValue)
                    {
                        fullExportPath = output.Value.Key;
                        await output.Value.Value.WriteAsync(exportData, 0, exportData.Length);

                        await output.Value.Value.FlushAsync();

                        output.Value.Value.Close();
                        success = true;
                    }

                    break;
                }

                default:
                {
                    String appDataPath = String.Empty;
                    devoctomy.DFramework.Core.IO.Directory.ResolvePath("{AppData}", out appDataPath);
                    if (!appDataPath.EndsWith(DLoggerManager.PathDelimiter))
                    {
                        appDataPath += DLoggerManager.PathDelimiter;
                    }
                    String vaultExportsPath = String.Format("{0}{1}", appDataPath, "Exports");
                    fullExportPath = String.Format("{0}\\{1}", vaultExportsPath, fileName);
                    try
                    {
                        await devoctomy.cachy.Framework.Native.Native.FileHandler.WriteAsync(fullExportPath, exportData);

                        success = true;
                    }
                    catch (Exception)
                    { }
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                App.AppLogger.Logger.Log(devoctomy.DFramework.Logging.Interfaces.LoggerMessageType.Exception, "Failed to export credentials. {0}", ex.ToString());
            }

            if (success)
            {
                Credential credential = Vault.CreateCredential();
                credential.GlyphKey    = Fonts.CachyFont.Glyph.Export.ToString();
                credential.GlyphColour = "Red";
                credential.Name        = name;
                credential.Description = "Password protected ZIP export.";
                credential.Notes       = fullExportPath;
                credential.Password    = passsword;
                credential.AddToVault(true);

                if (AppConfig.Instance.AutoSave && AppConfig.Instance.AutoSaveOnDuplicatingCred)
                {
                    Common.SaveResult saveResult = await Save();

                    if (saveResult == Common.SaveResult.Success)
                    {
                        VaultIndexFile.Invalidate();
                    }
                }

                NotifyPropertyChanged("FilteredCredentials");

                await App.Controller.MainPageInstance.DisplayAlert("Export Credentials",
                                                                   String.Format("Export was successful, the password for the export ZIP file has been placed in your vault, under the name '{0}'. Please remember to lock your vault to save the credential if you do not have aut-save enabled.", name),
                                                                   "OK");
            }
        }
コード例 #15
0
        private void Generate()
        {
            if (Memorable)
            {
                try
                {
                    string format = String.Empty;
                    if (RandomFormat)
                    {
                        List <string> formatParts = new List <string>();
                        formatParts.Add("{adjective:rc}");
                        formatParts.Add("{noun:rc}");
                        formatParts.Add("{verb:rc}");
                        formatParts.Add("{special1:1}");
                        formatParts.Add("{int:1-100}");
                        while (formatParts.Count > 0)
                        {
                            if (formatParts.Count > 0)
                            {
                                int randomIndex = SimpleRandomGenerator.QuickGetRandomInt(0, formatParts.Count);
                                format += formatParts[randomIndex];
                                formatParts.RemoveAt(randomIndex);
                            }
                            else
                            {
                                format += formatParts[0];
                                formatParts.RemoveAt(0);
                            }
                        }
                    }
                    else
                    {
                        format = MemorableFormat;
                    }
                    Password = Dictionaries.Instance.GeneratePhrase(format);
                }
                catch (Exception)
                {
                    Password = "******";
                }
            }
            else
            {
                SimpleRandomGenerator.CharSelection charSelection = SimpleRandomGenerator.CharSelection.None;
                if (UseDigits)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Digits;
                }
                if (UseLowercase)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Lowercase;
                }
                if (UseUppercase)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Uppercase;
                }
                if (UseSpecial && UseBrackets)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Brackets;
                }
                if (UseSpecial && UseMinus)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Minus;
                }
                if (UseSpecial && UseOther)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Other;
                }
                if (UseSpecial && UseSpace)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Space;
                }
                if (UseSpecial && UseUnderline)
                {
                    charSelection |= SimpleRandomGenerator.CharSelection.Underline;
                }

                Password = SimpleRandomGenerator.QuickGetRandomString(charSelection, Length, AtLeastOneOfEach);
            }
        }
コード例 #16
0
        public Boolean Process()
        {
            Boolean retVal = false;

            try
            {
                _state = Common.NodeState.Processing;

                DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Processing AESEncryptNode.");

                Boolean randomIV = false;
                if (IV.Value == null)
                {
                    Byte[] iv = SimpleRandomGenerator.QuickGetRandomBytes(16);
                    IV.SetValue(iv);
                    randomIV = true;
                }

                Byte[] inBlock = UnicodeEncoding.Unicode.GetBytes((String)PlainText.Value);
                DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating AES encryptor.");
                DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Key = {0}.", ((Byte[])Key.Value).ToPrettyString());
                DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "IV = {0}.", ((Byte[])IV.Value).ToPrettyString());
                DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Input = {0}.", inBlock.ToPrettyString());

                Byte[] outBlock = AESUtility.EncryptBytes(inBlock, (Byte[])Key.Value, (Byte[])IV.Value);

                if (randomIV)
                {
                    using (MemoryStream dataWithIV = new MemoryStream())
                    {
                        dataWithIV.Write(IV.Value, 0, IV.Value.Length);
                        dataWithIV.Write(outBlock, 0, outBlock.Length);
                        dataWithIV.Flush();
                        _encryptedData.SetValue(dataWithIV.ToArray());
                    }
                }
                else
                {
                    _encryptedData.SetValue(outBlock);
                }

                retVal = true;
            }
            finally
            {
                _state = Common.NodeState.Processed;
                if (retVal)
                {
                    Processed?.Invoke(this, EventArgs.Empty);
                }
            }
            if (retVal)
            {
                if (_next != null && _next.Length > 0)
                {
                    return(_next[0].Process());
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #17
0
        public object Write(
            object data, 
            string masterPassphrase,
            params KeyValuePair<string, string>[] parameters)
        {
            if (data.GetType() != typeof(Vault)) throw new ArgumentException("Data must be of type 'Vault'.", "data");

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing Vault to AES encrypted byte array.");

            Dictionary<string, string> parametersDict = parameters.ToDictionary(x => x.Key, x => x.Value);

            Vault dataVault = (Vault)data;

            JSONVaultSerialiser jsonSerialiser = new JSONVaultSerialiser();
            JObject json = (JObject)jsonSerialiser.Write(dataVault, String.Empty, parameters);

            String jsonString = json.ToString(Newtonsoft.Json.Formatting.None, null);
            Byte[] salt = SimpleRandomGenerator.QuickGetRandomBytes(16);

            GraphBuilder decryptGraph = new GraphBuilder("AESEncryptedVaultSerialiser.Read");
            GraphIO<String> unencryptedInput = new GraphIO<String>(jsonString);
            GraphIO<Byte[]> saltInput = new GraphIO<Byte[]>(salt);

            //create derive node here
            IGraphNode keyDerivationNode = null;

            if (parametersDict.ContainsKey("KeyDerivationFunction"))
            {
                string keyDerivationFunction = parametersDict["KeyDerivationFunction"];
                switch (keyDerivationFunction)
                {
                    case "PBKDF2":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    case "SCRYPT":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            int blockSize = int.Parse(parametersDict["BlockSize"]);
                            int threadCount = int.Parse(parametersDict["ThreadCount"]);
                            keyDerivationNode = new SCryptDeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount), new GraphIO<int>(blockSize), new GraphIO<int>(threadCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    default:
                        {
                            throw new InvalidOperationException(String.Format("Unknown key derivation function '{0}'.", keyDerivationFunction));
                        }
                }
            }
            else
            {
                //default setup
                keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(10000));
                decryptGraph.AddNode("deriveNode", keyDerivationNode);
            }

            AESEncryptNode encryptNode = new AESEncryptNode(unencryptedInput, new GraphIO<Byte[]>(null), keyDerivationNode.GetBytesIO("DerivedKey"));

            decryptGraph.AddNode("encryptNode", encryptNode);
            decryptGraph.CreateRoute("encrypt",
                keyDerivationNode.GetStringIO("Password"),
                encryptNode.EncryptedData,
                "deriveNode",
                new String[] { "deriveNode", "encryptNode" });

            Object output = null;
            if (decryptGraph.Process(true, "encrypt", masterPassphrase, out output))
            {
                byte[] encrypted = (byte[])output;
                byte[] encryptedWithSalt = encrypted.AppendBytes(salt);
                return (encryptedWithSalt);
            }
            else
            {
                throw new Exception("Failed to encrypt Vault.");
            }

            throw new NotImplementedException();
        }
コード例 #18
0
ファイル: Dictionaries.cs プロジェクト: devoctomy/cachy
        public string GeneratePhrase(string format)
        {
            string phrase = format;

            //we do this in a loop so we can replace individual tokens as we go
            Regex tokenRegex = new Regex("\\{(.*?)\\}");
            Dictionary <string, string> invalidTokens = new Dictionary <string, string>();
            MatchCollection             tokens        = tokenRegex.Matches(phrase);

            while (tokens.Count > 0)
            {
                Match firstMatch = tokens[0];

                string   token      = firstMatch.Value.Trim(new char[] { '{', '}' });
                string[] tokenParts = token.Split(':');
                if (tokenParts.Length == 2)
                {
                    string randomWord = String.Empty;
                    switch (tokenParts[0])
                    {
                    case "verb":
                    {
                        randomWord = SimpleRandomGenerator.QuickGetRandomStringArrayEntry(Verbs.ToArray());
                        break;
                    }

                    case "adjective":
                    {
                        randomWord = SimpleRandomGenerator.QuickGetRandomStringArrayEntry(Adjectives.ToArray());
                        break;
                    }

                    case "noun":
                    {
                        randomWord = SimpleRandomGenerator.QuickGetRandomStringArrayEntry(Nouns.ToArray());
                        break;
                    }

                    case "int":
                    {
                        randomWord = "{int}";
                        break;
                    }

                    case "special1":
                    {
                        randomWord = "{special1}";
                        break;
                    }

                    default:
                    {
                        randomWord = "{invalid}";
                        break;
                    }
                    }
                    bool replace = true;
                    switch (randomWord)
                    {
                    case "{int}":
                    {
                        string   range      = tokenParts[1];
                        string[] rangeParts = range.Split('-');
                        int      min        = int.Parse(rangeParts[0]);
                        int      max        = int.Parse(rangeParts[1]);
                        if (max > min)
                        {
                            int randomInt = SimpleRandomGenerator.QuickGetRandomInt(min, max);
                            randomWord = randomInt.ToString();
                        }
                        else
                        {
                            randomWord = String.Empty;
                        }
                        break;
                    }

                    case "{special1}":
                    {
                        int count = int.Parse(tokenParts[1]);
                        randomWord = SimpleRandomGenerator.QuickGetRandomString(
                            SimpleRandomGenerator.CharSelection.Minus |
                            SimpleRandomGenerator.CharSelection.Underline,
                            count,
                            false);
                        break;
                    }

                    case "{invalid}":
                    {
                        string tempReplacement = String.Format("[invalidtoken:{0}]", invalidTokens.Count);
                        invalidTokens.Add(tempReplacement, firstMatch.Value);
                        phrase  = phrase.Remove(firstMatch.Index, firstMatch.Length);
                        phrase  = phrase.Insert(firstMatch.Index, tempReplacement);
                        replace = false;
                        break;
                    }

                    default:
                    {
                        string casing = tokenParts[1];
                        if (casing == "rc")
                        {
                            casing = SimpleRandomGenerator.QuickGetRandomStringArrayEntry(new string[] { "lc", "uc", "ic" });
                        }
                        switch (casing)
                        {
                        case "lc":
                        {
                            randomWord = randomWord.ToLower();
                            break;
                        }

                        case "uc":
                        {
                            randomWord = randomWord.ToUpper();
                            break;
                        }

                        case "ic":
                        {
                            randomWord = randomWord[0].ToString().ToUpper() + randomWord.Substring(1);
                            break;
                        }
                        }
                        break;
                    }
                    }
                    if (replace)
                    {
                        phrase = phrase.Remove(firstMatch.Index, firstMatch.Length);
                        phrase = phrase.Insert(firstMatch.Index, randomWord);
                    }
                }
                else
                {
                    //invalid token, remove it so that we don't get stuck in the loop
                    string tempReplacement = String.Format("[invalidtoken:{0}]", invalidTokens.Count);
                    invalidTokens.Add(tempReplacement, firstMatch.Value);
                    phrase = phrase.Remove(firstMatch.Index, firstMatch.Length);
                    phrase = phrase.Insert(firstMatch.Index, tempReplacement);
                }

                tokens = tokenRegex.Matches(phrase);
            }

            foreach (string token in invalidTokens.Keys)
            {
                if (phrase.Contains(token))
                {
                    phrase = phrase.Replace(token, invalidTokens[token]);
                }
            }

            return(phrase);
        }
コード例 #19
0
        public static Credential CreateRandomCredential(
            Random rng,
            out string id,
            out string glyphKey,
            out string glyphColour,
            out string name,
            out string description,
            out string website,
            out DateTime createdAt,
            out DateTime lastModifiedAt,
            out DateTime passwordLastModifiedAt,
            out string username,
            out string password,
            out string[] tags,
            out string notes,
            out AuditLogEntry[] auditLogEntries)
        {
            id                     = Guid.NewGuid().ToString();
            glyphKey               = "None";
            glyphColour            = "Black";
            name                   = Guid.NewGuid().ToString();
            description            = Guid.NewGuid().ToString();
            website                = Guid.NewGuid().ToString();
            createdAt              = new DateTime(1982, 4, 3, rng.Next(0, 24), rng.Next(0, 60), rng.Next(0, 60));
            lastModifiedAt         = createdAt.Add(new TimeSpan(rng.Next(0, 101), rng.Next(0, 24), rng.Next(0, 60), rng.Next(0, 60)));
            passwordLastModifiedAt = createdAt.Add(new TimeSpan(rng.Next(0, 101), rng.Next(0, 24), rng.Next(0, 60), rng.Next(0, 60)));
            username               = SimpleRandomGenerator.QuickGetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 12) + "@" + SimpleRandomGenerator.QuickGetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 6) + ".com";
            password               = SimpleRandomGenerator.QuickGetRandomString(SimpleRandomGenerator.CharSelection.All, 16, true);
            List <String> tagsList = new List <String>();

            while (tagsList.Count < 10)
            {
                tagsList.Add(Guid.NewGuid().ToString());
            }
            tags  = tagsList.ToArray();
            notes = SimpleRandomGenerator.QuickGetRandomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 256);
            List <AuditLogEntry> auditLogEntriesList = new List <AuditLogEntry>();

            while (auditLogEntriesList.Count < 100)
            {
                auditLogEntriesList.Add(AuditLogEntryTests.CreateRandomAuditLogEntry(rng));
            }
            auditLogEntries = auditLogEntriesList.ToArray();

            Credential credential = new Credential(id,
                                                   glyphKey,
                                                   glyphColour,
                                                   name,
                                                   description,
                                                   website,
                                                   createdAt,
                                                   lastModifiedAt,
                                                   passwordLastModifiedAt,
                                                   username,
                                                   password,
                                                   tags,
                                                   notes,
                                                   auditLogEntries);

            return(credential);
        }