示例#1
0
        private async void GetEntries(string passwd)
        {
            if (!KeyProvider.CorrectPassword(passwd))
            {
                RaiseGetEntriesFailed();
                return;
            }
            var task = new Task <List <JournalEntry> >(() =>
            {
                return(_entriesProvider.GetEntries(passwd));
            });

            task.Start();
            var result = new List <JournalEntry>();

            try
            {
                result = await task;
                RaiseGetEntriesCompleted();
            }
            catch (Exception)
            {
                RaiseGetEntriesFailed();
            }
            this.Entries = new ObservableCollection <JournalEntry>(result);
        }
        public string Decrypt(string encryptedContent, string password)
        {
            if (!KeyProvider.CorrectPassword(password))
            {
                throw new Exception("Password isn`t correct");
            }
            var    buffer = Convert.FromBase64String(encryptedContent);
            string decrypted;
            var    transform = GetDecryptor();

            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                {
                    cs.Write(buffer, 0, buffer.Length);

                    cs.FlushFinalBlock();
                    cs.Clear();
                    cs.Close();
                    decrypted = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();
                }
            }
            return(decrypted);
        }
        public virtual void TestCache()
        {
            KeyProviderCache kpCache = new KeyProviderCache(10000);
            Configuration    conf    = new Configuration();

            conf.Set(DFSConfigKeys.DfsEncryptionKeyProviderUri, "dummy://*****:*****@test_provider1"
                     );
            KeyProvider keyProvider1 = kpCache.Get(conf);

            NUnit.Framework.Assert.IsNotNull("Returned Key Provider is null !!", keyProvider1
                                             );
            conf.Set(DFSConfigKeys.DfsEncryptionKeyProviderUri, "dummy://*****:*****@test_provider1"
                     );
            KeyProvider keyProvider2 = kpCache.Get(conf);

            NUnit.Framework.Assert.IsTrue("Different KeyProviders returned !!", keyProvider1
                                          == keyProvider2);
            conf.Set(DFSConfigKeys.DfsEncryptionKeyProviderUri, "dummy://test_provider3");
            KeyProvider keyProvider3 = kpCache.Get(conf);

            NUnit.Framework.Assert.IsFalse("Same KeyProviders returned !!", keyProvider1 == keyProvider3
                                           );
            conf.Set(DFSConfigKeys.DfsEncryptionKeyProviderUri, "dummy://*****:*****@test_provider1"
                     );
            KeyProvider keyProvider4 = kpCache.Get(conf);

            NUnit.Framework.Assert.IsFalse("Same KeyProviders returned !!", keyProvider1 == keyProvider4
                                           );
        }
示例#4
0
文件: App.xaml.cs 项目: phaufe/carnac
 public App()
 {
     settingsProvider = new SettingsProvider(new RoamingAppDataStorage("Carnac"));
     keyProvider      = new KeyProvider(InterceptKeys.Current, new PasswordModeService(), new DesktopLockEventService());
     settings         = settingsProvider.GetSettings <PopupSettings>();
     messageProvider  = new MessageProvider(new ShortcutProvider(), settings, new MessageMerger());
 }
示例#5
0
        private Message Decrypt(SecureMessageContainer container)
        {
            Message msg = null;

            RijndaelManaged rmCrypto = new RijndaelManaged();

            byte[] key = KeyProvider.Decrypt(Convert.FromBase64String(container.EncryptedKey));
            byte[] iv  = KeyProvider.Decrypt(Convert.FromBase64String(container.EncryptedIV));

            using (MemoryStream encrypted = new MemoryStream(Convert.FromBase64String(container.EncryptedData)))
                using (CryptoStream cs = new CryptoStream(encrypted, rmCrypto.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                {
                    byte[] buffer = new byte[encrypted.Length];

                    int bytesRead = cs.Read(buffer, 0, (int)encrypted.Length);

                    using (MemoryStream decrypted = new MemoryStream(bytesRead))
                    {
                        decrypted.Write(buffer, 0, bytesRead);
                        decrypted.Position = 0;

                        DataContractSerializer serializer = new DataContractSerializer(typeof(Message));
                        msg = (Message)serializer.ReadObject(decrypted);
                    }
                }

            return(msg);
        }
        public JsonResult Login(string system, string username, string password)
        {
            if (!this.model.IsLoginRequired(system))
            {
                return(this.Json(new { isSuccess = true }));
            }

            try
            {
                if (this.model.Login(system, username, password))
                {
                    var cookie           = this.HttpContext.Request.Cookies.Get("sqleditor");
                    var userKey          = cookie != null ? cookie.Value : string.Empty;
                    var connString       = this.model.GetUserConnectionString(system, username, password).ConnectionString;
                    var cryptoConnString = Crypto.Encrypt(connString, KeyProvider.GetUserSpecificSecretKey(userKey));
                    this.Session.Add(system, cryptoConnString);
                    return(this.Json(new { isSuccess = true }));
                }
            }
            catch (Exception ex)
            {
                return(this.Json(new { isSuccess = false, message = ex.Message }));
            }

            return(this.Json(new { isSuccess = false }));
        }
        private ICryptoTransform GetDecryptor()
        {
            var rijndael = new RijndaelManaged {
                Key = KeyProvider.GetKey(), IV = KeyProvider.GetIV()
            };

            return(rijndael.CreateDecryptor());
        }
示例#8
0
        protected override void LoadContent()
        {
            Key         = Game.Services.GetService(typeof(KeyProvider)) as KeyProvider;
            ScreenSize  = new Vector2(Game.GraphicsDevice.Viewport.Width, Game.GraphicsDevice.Viewport.Height);
            spriteBatch = new SpriteBatch(GraphicsDevice);

            base.LoadContent();
        }
        public void KeyProvider_InvalidKey_ReturnsInvalidKey()
        {
            var provider = new KeyProvider();

            var key = provider.InvalidKey();

            Assert.IsFalse(provider.IsValid(key));
        }
示例#10
0
        /* Helper function to create a key in the Key Provider. */
        /// <exception cref="Sharpen.NoSuchAlgorithmException"/>
        /// <exception cref="System.IO.IOException"/>
        private void CreateAKey(string keyName, Configuration conf)
        {
            KeyProvider provider = dfsCluster.GetNameNode().GetNamesystem().GetProvider();

            KeyProvider.Options options = KeyProvider.Options(conf);
            provider.CreateKey(keyName, options);
            provider.Flush();
        }
示例#11
0
        public KeyProviderTests()
        {
            _memoryCache = new MemoryCache(new MemoryCacheOptions());

            _keyRepositoryMock = new Mock <IKeyRepository>();

            _keyProvider = new KeyProvider(_keyRepositoryMock.Object, _memoryCache);
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string key             = KeyProvider.ProvideKey(new[] { value });
            var    cultureInfo     = value as CultureInfo;
            object localizedObject = CommonResourceManager.Instance.GetResourceObject(key, cultureInfo);

            return(localizedObject ?? ResXExtension.GetDefaultValue(key));
        }
示例#13
0
        private static Key GetKey(int cardSet, int discardsCount = 0, int otherSuitsDistribution = 0, bool isOwnMove = false)
        {
            Debug.Assert(cardSet <= CardSet.MaxValue);

            KeyProvider provider = GetKeyProvider(cardSet, isOwnMove);

            return(provider.CreateKey(cardSet, discardsCount, otherSuitsDistribution, isOwnMove));
        }
示例#14
0
        private IEnumerable <KeyPress> ToEnumerable(KeyProvider provider, KeyPlayer player)
        {
            var keys = new List <KeyPress>();

            provider.Subscribe(keys.Add);
            player.Play();

            return(keys);
        }
示例#15
0
        public Index(INodeTracker <TValue> nodeTracker, KeyProvider <TKey, TValue> keyProvider)
        {
            _nodeTracker = nodeTracker;
            _keyProvider = keyProvider;

            _index = new Dictionary <TKey, WeakReference <INode <TValue> > >();

            _nodeTracker.Connect(this);
        }
        public void KeyProvider_CallingKeyTwice_ReturnsNewKeyEachTime()
        {
            var provider = new KeyProvider();

            var key1 = provider.Key();
            var key2 = provider.Key();

            Assert.AreNotEqual(key1, key2);
        }
示例#17
0
        public virtual IStorageLocation GetLocation(IMediaId id)
        {
            string            key       = KeyProvider.GetStorageKey(id);
            IStorageContainer container = GetContainer(KeyProvider.GetContainerName(key));
            var location = container.GetLocation(KeyProvider.GetLocationName(key), id);


            return(location);
        }
示例#18
0
        /// <summary>
        /// Returns localized string (object) by composite key.
        /// Key parts are in <paramref name="values"/> except last member of array.
        /// Last member is <see cref="CultureInfo"/>
        /// Firstly <see cref="KeyProvider"/> makes key from it's BaseKey and key parts from <paramref name="values"/>.
        /// Then localized object returned from resources depending on this key
        /// </summary>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Parameters.Count + 1 != values.Length)
            {
                throw new ArgumentException(string.Format("ResConverter - parameters count error. Parameters.Count = {0}, values.Count = {1}", Parameters.Count, values.Length));
            }
            // values are the mix from ResKeyParts and ResParams. And culture in last parameter.
            // Separate them as Cinderella to different heaps.
            var resKeyParts = new List <object>();
            var resParams   = new List <object>();

            for (int i = 0; i < Parameters.Count; i++)
            {
                object      value = values[i];
                BindingBase param = Parameters[i];
                if (param is ResKeyPart)
                {
                    if (value == DependencyProperty.UnsetValue && param.FallbackValue != null)
                    {
                        value = param.FallbackValue;
                    }
                    if (value != null)
                    {
                        resKeyParts.Add(value);
                    }
                }
                else if (param is ResParam)
                {
                    resParams.Add(value);
                }
            }
            CultureInfo cultureInfo = values[values.Length - 1] as CultureInfo;

            string key             = KeyProvider.ProvideKey(resKeyParts);
            object localizedObject = ResManager.Instance.GetResourceObject(key, cultureInfo) ??
                                     ResManager.Instance.GetResourceObject(ResExtension.Key, cultureInfo);

            if (localizedObject == null)
            {
                localizedObject = ResExtension.GetDefaultValue(key);
            }
            else
            {
                try
                {
                    if (resParams.Count > 0)
                    {
                        localizedObject = string.Format(localizedObject.ToString(), resParams.Cast <object>().ToArray());
                    }
                }
                catch (FormatException)
                {
                }
            }
            return(localizedObject);
        }
示例#19
0
        public MessageProviderFacts()
        {
            settingsProvider = Substitute.For <ISettingsProvider>();
            settingsProvider.GetSettings <PopupSettings>().Returns(new PopupSettings());
            shortcutProvider    = Substitute.For <IShortcutProvider>();
            interceptKeysSource = new Subject <InterceptKeyEventArgs>();
            var keyProvider = new KeyProvider(interceptKeysSource, new PasswordModeService());

            messageProvider = new MessageProvider(keyProvider, shortcutProvider, settingsProvider);
        }
示例#20
0
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            Check.Require(Parameters.Count + 1 == values.Length, string.Format("DH: ResXConverter - parameters count error. Parameters.Count = {0}, values.Count = {1}", Parameters.Count, values.Length));

            var resXKeyParts = new List <object>();
            var resXParams   = new List <object>();

            for (int i = 0; i < Parameters.Count; i++)
            {
                object value = values[i];

                BindingBase param = Parameters[i];

                if (param is ResXKeyPart)
                {
                    if (value == DependencyProperty.UnsetValue && param.FallbackValue != null)
                    {
                        value = param.FallbackValue;
                    }
                    if (value != null)
                    {
                        resXKeyParts.Add(value);
                    }
                }
                else if (param is ResXParam)
                {
                    resXParams.Add(value);
                }
            }

            CultureInfo cultureInfo = values[values.Length - 1] as CultureInfo;

            string key = KeyProvider.ProvideKey(resXKeyParts);

            object localizedObject = CommonResourceManager.Instance.GetResourceObject(key, cultureInfo) ??
                                     CommonResourceManager.Instance.GetResourceObject(ResXExtension.Key, cultureInfo);

            if (localizedObject == null)
            {
                localizedObject = ResXExtension.GetDefaultValue(key);
            }
            else
            {
                try
                {
                    localizedObject = string.Format(localizedObject.ToString(), resXParams.Cast <object>().ToArray());
                }
                catch
                {
                }
            }

            return(localizedObject);
        }
示例#21
0
        public static void From_IKeyProvider()
        {
            // Arrange
            var model = new KeyProvider();

            // Act
            var result = Key.From(model);

            // Assert
            Assert.Equal("x", result);
        }
示例#22
0
        public void verify_shift_number()
        {
            // arrange
            var player   = KeyStreams.ExclaimationMark();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService);

            // act
            var processedKeys = ToEnumerable(provider, player);

            // assert
            Assert.Equal(new[] { "!" }, processedKeys.Single().Input);
        }
示例#23
0
        public async Task key_without_shift_is_lowercase()
        {
            // arrange
            var player   = KeyStreams.LetterL();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService, settingsProvider);

            // act
            var processedKeys = await provider.GetKeyStream().ToList();

            // assert
            Assert.Equal(new[] { "l" }, processedKeys.Single().Input);
        }
        MessageProvider CreateMessageProvider(IObservable <InterceptKeyEventArgs> keysStreamSource)
        {
            var source = Substitute.For <IInterceptKeys>();

            source.GetKeyStream().Returns(keysStreamSource);
            var desktopLockEventService = Substitute.For <IDesktopLockEventService>();

            desktopLockEventService.GetSessionSwitchStream().Returns(Observable.Never <SessionSwitchEventArgs>());
            var keyProvider = new KeyProvider(source, new PasswordModeService(), desktopLockEventService);

            return(new MessageProvider(shortcutProvider, keyProvider, new PopupSettings(), new MessageMerger()));
        }
示例#25
0
        public async Task verify_shift_number()
        {
            // arrange
            var player   = KeyStreams.ExclaimationMark();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService, settingsProvider);

            // act
            var processedKeys = await provider.GetKeyStream().ToList();

            // assert
            Assert.Equal(new[] { "!" }, processedKeys.Single().Input);
        }
示例#26
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    KeyProvider.Dispose();
                }

                disposedValue = true;
            }
        }
示例#27
0
        public void key_without_shift_is_lowercase()
        {
            // arrange
            var player   = KeyStreams.LetterL();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService);

            // act
            var processedKeys = ToEnumerable(provider, player);

            // assert
            Assert.Equal(new[] { "l" }, processedKeys.Single().Input);
        }
示例#28
0
        public async Task ctrlshiftl_is_processed_correctly()
        {
            // arrange
            var player   = KeyStreams.CtrlShiftL();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService, settingsProvider);

            // act
            var processedKeys = await provider.GetKeyStream().ToList();

            // assert
            Assert.Equal(new[] { "Ctrl", "Shift", "L" }, processedKeys.Single().Input);
        }
示例#29
0
        public void keyprovider_detects_windows_key_presses()
        {
            // arrange
            var player   = KeyStreams.WinkeyE();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService);

            // act
            var processedKeys = ToEnumerable(provider, player);

            // assert
            Assert.Equal(new[] { "Win", "e" }, processedKeys.Single().Input);
        }
示例#30
0
        public async Task keyprovider_detects_windows_key_presses()
        {
            // arrange
            var player   = KeyStreams.WinkeyE();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService, settingsProvider);

            // act
            var processedKeys = await provider.GetKeyStream().ToList();

            // assert
            Assert.Equal(new[] { "Win", "e" }, processedKeys.Single().Input);
        }
示例#31
0
        /// <summary>
        /// Adds a keyfile to a <see cref="CompositeKey"/>.
        /// </summary>
        /// <param name="keyFilePath">The path to the keyfile to add to the <see cref="CompositeKey"/>.</param>
        /// <param name="key">The <see cref="CompositeKey"/> to add the keyfile to.</param>
        /// <param name="connectionInfo">The <see cref="IOConnectionInfo"/> object of the database (required for <see cref="KeyProviderQueryContext"/>).</param>
        /// <returns>true if sucessfull, false otherwise.</returns>
        public static bool AddKeyfileToKey(string keyFilePath, CompositeKey key, IOConnectionInfo connectionInfo)
        {
            bool success = false;

            if (!File.Exists(keyFilePath))
            {
                return(false);
            }

            bool bIsKeyProv = Program.KeyProviderPool.IsKeyProvider(keyFilePath);

            if (!bIsKeyProv)
            {
                try
                {
                    key.AddUserKey(new KcpKeyFile(keyFilePath, true));
                    success = true;
                }
                catch (InvalidDataException exId)
                {
                    MessageService.ShowWarning(keyFilePath, exId);
                }
                catch (Exception exKf)
                {
                    MessageService.ShowWarning(keyFilePath, KPRes.KeyFileError, exKf);
                }
            }
            else
            {
                KeyProviderQueryContext ctxKp = new KeyProviderQueryContext(connectionInfo, true, false);

                KeyProvider prov         = Program.KeyProviderPool.Get(keyFilePath);
                bool        bPerformHash = !prov.DirectKey;
                byte[]      pbCustomKey  = prov.GetKey(ctxKp);

                if ((pbCustomKey != null) && (pbCustomKey.Length > 0))
                {
                    try
                    {
                        key.AddUserKey(new KcpCustomKey(keyFilePath, pbCustomKey, bPerformHash));
                        success = true;
                    }
                    catch (Exception exCkp)
                    {
                        MessageService.ShowWarning(exCkp);
                    }

                    MemUtil.ZeroByteArray(pbCustomKey);
                }
            }

            return(success);
        }
示例#32
0
        public void ctrlshiftl_is_processed_correctly()
        {
            // arrange
            var player   = KeyStreams.CtrlShiftL();
            var provider = new KeyProvider(player, passwordModeService, desktopLockEventService);

            // act
            var processedKeys = ToEnumerable(provider, player);

            // assert
            Assert.Equal(new[] { "Ctrl", "Shift", "L" }, processedKeys.Single().Input);
        }
        public void KeyProvider_Key_ReturnsKey()
        {
            var provider = new KeyProvider();

            var key = provider.Key();
        }