public void SymmetricKeyCanBeRecovered()
        {
            key = ProtectedKey.CreateFromEncryptedKey(encryptedKey, DataProtectionScope.LocalMachine);

            byte[] recoveredKey = key.DecryptedKey;

            AssertHelpers.AssertArraysEqual(symmetricAlgo.Key, recoveredKey);
        }
Esempio n. 2
0
        /// <summary>
        /// Initialize a new instance of the <see cref="ExportKeyUI"/> class.
        /// </summary>
        public ExportKeyUI(ProtectedKey key)
        {
            this.key = key;
            InitializeComponent();

            btnCancel.Text = Resources.ExportKeyUICancelButton;
            btnOk.Text = Resources.ExportKeyUIOkButton;
            Text = Resources.ExportKeyDialogTitle;
        }
Esempio n. 3
0
        public void SetUp()
        {
            DatabaseProviderFactory dbFactory = new DatabaseProviderFactory(ConfigurationSourceFactory.Create());

            db = dbFactory.CreateDefault();
            unencryptedBackingStore = new DataBackingStore(db, "encryptionTests", null);
            unencryptedBackingStore.Flush();

            ProtectedKey key = KeyManager.GenerateSymmetricKey(typeof(RijndaelManaged), DataProtectionScope.CurrentUser);

            using (FileStream stream = new FileStream("ProtectedKey.file", FileMode.Create))
            {
                KeyManager.Write(stream, key);
            }
        }
Esempio n. 4
0
        public void SymmetricKeysCanBeArchivedToStream()
        {
            byte[]       keyToBeArchived = GenerateKeyToBeArchived();
            ProtectedKey key             = ProtectedKey.CreateFromPlaintextKey(keyToBeArchived, DataProtectionScope.LocalMachine);

            IKeyWriter writer = new KeyReaderWriter();

            writer.Archive(stream, key, passphrase);

            stream.Seek(0, SeekOrigin.Begin);

            IKeyReader   reader      = new KeyReaderWriter();
            ProtectedKey restoredKey = reader.Restore(stream, passphrase, DataProtectionScope.LocalMachine);

            AssertHelpers.AssertArraysEqual(keyToBeArchived, restoredKey.DecryptedKey);
        }
Esempio n. 5
0
        public void EncryptAndDecryptWithTypeUsingProtectedKey()
        {
            byte[] key = new byte[16];
            CryptographyUtility.GetRandomBytes(key);
            ProtectedKey protectedKey = ProtectedKey.CreateFromPlaintextKey(key, DataProtectionScope.LocalMachine);

            SymmetricCryptographer symm = new SymmetricCryptographer(typeof(RijndaelManaged), protectedKey);

            byte[] plainText = new byte[12];
            CryptographyUtility.GetRandomBytes(plainText);

            byte[] cipherText = symm.Encrypt(plainText);
            Assert.IsFalse(CryptographyUtility.CompareBytes(cipherText, plainText));

            byte[] decryptedText = symm.Decrypt(cipherText);
            Assert.IsTrue(CryptographyUtility.CompareBytes(plainText, decryptedText));
        }
        public void SetUp()
        {
            // to force mstest to copy the assembly
            var ignored = typeof(Caching.Cryptography.SymmetricStorageEncryptionProvider).GetConstructors();

            DatabaseProviderFactory dbFactory = new DatabaseProviderFactory(ConfigurationSourceFactory.Create());

            db = dbFactory.CreateDefault();
            unencryptedBackingStore = new DataBackingStore(db, "encryptionTests", null);
            unencryptedBackingStore.Flush();

            ProtectedKey key = KeyManager.GenerateSymmetricKey(typeof(RijndaelManaged), DataProtectionScope.CurrentUser);

            using (FileStream stream = new FileStream("ProtectedKey.file", FileMode.Create))
            {
                KeyManager.Write(stream, key);
            }
        }
Esempio n. 7
0
 public void SetPlainSecret(string secret)
 {
     if (this.Encoding == OtpSecretEncoding.Base32)
     {
         this.Key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(KeePassLib.Utility.MemUtil.ParseBase32(secret));
     }
     else if (this.Encoding == OtpSecretEncoding.Base64)
     {
         this.Key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(Convert.FromBase64String(secret));
     }
     else if (this.Encoding == OtpSecretEncoding.Hex)
     {
         this.Key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(KeePassLib.Utility.MemUtil.HexStringToByteArray(secret));
     }
     else if (this.Encoding == OtpSecretEncoding.UTF8)
     {
         this.Key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(KeePassLib.Utility.StrUtil.Utf8.GetBytes(secret));
     }
 }
        private void btnFinish_Click(object sender, EventArgs e)
        {
            switch (supplyKeyControl.Method)
            {
            case SupplyKeyMethod.OpenExisting:
                using (Stream importedKeyReader = File.OpenRead(openExistingKeyFileControl.Filepath))
                {
                    try
                    {
                        protectedKeySettings.ProtectedKey = KeyManager.Read(importedKeyReader, chooseDpapiScopeControl.Scope);
                        protectedKeySettings.Scope        = chooseDpapiScopeControl.Scope;
                    }
                    catch (Exception)
                    {
                        MessageBox.Show(Resources.ErrorImportingKey, Resources.CryptoKeyWizardErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                break;

            case SupplyKeyMethod.CreateNew:
                protectedKeySettings.ProtectedKey = ProtectedKey.CreateFromPlaintextKey(createNewKeyControl.Key, chooseDpapiScopeControl.Scope);
                protectedKeySettings.Scope        = chooseDpapiScopeControl.Scope;
                break;

            case SupplyKeyMethod.ImportKey:
                using (Stream archivedKeyReader = File.OpenRead(importArchivedKeyControl.Filename))
                {
                    try
                    {
                        protectedKeySettings.ProtectedKey = KeyManager.RestoreKey(archivedKeyReader, importArchivedKeyControl.Passphrase, chooseDpapiScopeControl.Scope);
                        protectedKeySettings.Scope        = chooseDpapiScopeControl.Scope;
                    }
                    catch (CryptographicException)
                    {
                        MessageBox.Show(Resources.KeyCouldNotBeRead, Resources.CryptoKeyWizardErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        this.DialogResult = DialogResult.None;
                    }
                }
                break;
            }
        }
        public static string Encriptar(string texto, out Object keysimetric)
        {
            string result = "";

            try
            {
                ProtectedKey key = KeyManager.GenerateSymmetricKey("System.Security.Cryptography.TripleDESCryptoServiceProvider", DataProtectionScope.LocalMachine);

                SymmetricAlgorithmProvider provider = new SymmetricAlgorithmProvider(typeof(TripleDESCryptoServiceProvider), key);
                result      = Convert.ToBase64String(provider.Encrypt(UnicodeEncoding.Unicode.GetBytes(texto.ToCharArray(), 0, texto.Length)));
                keysimetric = key;

                //string decryptedData = UnicodeEncoding.Unicode.GetString(provider.Decrypt(Convert.FromBase64String(result)));
                //var crypto = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>();
                //result = crypto.EncryptSymmetric(GetSymmProvider(), texto);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
        public static string Desencriptar(string textoEncriptado)
        {
            string result = "";

            try
            {
                string       ruta = AppDomain.CurrentDomain.BaseDirectory + "\\" + ConfigurationManager.AppSettings["EntLibSymmProvider"];
                ProtectedKey key  = (ProtectedKey) new ManejadorArchivos().LeerKey(ruta);
                SymmetricAlgorithmProvider provider = new SymmetricAlgorithmProvider(typeof(TripleDESCryptoServiceProvider), key);

                result = UnicodeEncoding.Unicode.GetString(provider.Decrypt(Convert.FromBase64String(textoEncriptado)));

                //ModifProtectedKeyFilename();
                //var crypto = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>();
                //string clavesimetrica = GetSymmProvider();
                //result = crypto.DecryptSymmetric(clavesimetrica, textoEncriptado);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }
Esempio n. 11
0
        public static OtpAuthData FromString(string data)
        {
            NameValueCollection parameters = ParseQueryString(data);

            if (parameters[keyParameter] == null)
            {
                throw new ArgumentException("Must have a key in the data");
            }

            var otpData = new OtpAuthData();

            otpData.Key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(Base32.Decode(parameters[keyParameter]));

            if (parameters[typeParameter] != null)
            {
                otpData.Type = (OtpType)Enum.Parse(typeof(OtpType), parameters[typeParameter]);
            }

            if (parameters[otpHashModeParameter] != null)
            {
                otpData.OtpHashMode = (OtpHashMode)Enum.Parse(typeof(OtpHashMode), parameters[otpHashModeParameter]);
            }

            if (otpData.Type == OtpType.Totp)
            {
                otpData.Step = GetIntOrDefault(parameters, stepParameter, 30);
            }
            else if (otpData.Type == OtpType.Hotp)
            {
                otpData.Counter = GetIntOrDefault(parameters, counterParameter, 0);
            }

            otpData.Size = GetIntOrDefault(parameters, sizeParameter, 6);

            return(otpData);
        }
Esempio n. 12
0
        public void SymmetricKeysCanBeGeneratedFromAlgorithmNames()
        {
            ProtectedKey generatedKey = symmetricKeyGenerator.GenerateKey("Rijndael", DataProtectionScope.CurrentUser);

            Assert.IsNotNull(generatedKey.EncryptedKey);
        }
Esempio n. 13
0
 public void SymmetricKeyCanBeProtected()
 {
     key = ProtectedKey.CreateFromEncryptedKey(encryptedKey, DataProtectionScope.LocalMachine);
     AssertHelpers.AssertArraysEqual(encryptedKey, key.EncryptedKey);
 }
 public void CreateKey()
 {
     key = KeyManager.GenerateKeyedHashKey(typeof(HMACSHA1), DataProtectionScope.CurrentUser);
 }
 public void CreateKey()
 {
     key = KeyManager.GenerateKeyedHashKey(typeof(HMACSHA1), DataProtectionScope.CurrentUser);
 }
Esempio n. 16
0
        public void SymmetricKeysCanBeGeneratedFromAlgorithmType()
        {
            ProtectedKey generatedKey = symmetricKeyGenerator.GenerateKey(typeof(RijndaelManaged), DataProtectionScope.CurrentUser);

            Assert.IsNotNull(generatedKey.EncryptedKey);
        }
 public AccessKey(ProtectedKey protectedKey) : base(protectedKey)
 {
 }
Esempio n. 18
0
 public void ProvidingNullFileNameThrowsArgumentException()
 {
     ProtectedKey neverActuallySetsThisVariable = cache[null];
 }
Esempio n. 19
0
 public void CreateStuff()
 {
     cache       = new ProtectedKeyCache();
     originalKey = KeyManager.GenerateSymmetricKey(typeof(RijndaelManaged), DataProtectionScope.LocalMachine);
 }
Esempio n. 20
0
 public void ConstructWithNullInstrumentationProviderThrows()
 {
     new SymmetricAlgorithmProvider(typeof(RijndaelManaged), ProtectedKey.CreateFromPlaintextKey(new byte[] { 0x00, 0x01 }, DataProtectionScope.CurrentUser), null);
 }
Esempio n. 21
0
 public void ConstructWithNonSymmetricAlgorithmTypeThrows()
 {
     new SymmetricAlgorithmProvider(typeof(object), ProtectedKey.CreateFromPlaintextKey(new byte[] { 0x00, 0x01 }, DataProtectionScope.CurrentUser));
 }
		public void CreateStuff()
		{
			cache = new ProtectedKeyCache();
			originalKey = KeyManager.GenerateSymmetricKey(typeof(RijndaelManaged), DataProtectionScope.LocalMachine); 
		}
Esempio n. 23
0
 public void ProvidingEmptyFileNameThrowsArgumentException()
 {
     ProtectedKey neverActuallySetsThisVariable = cache[String.Empty];
 }
Esempio n. 24
0
        private void OtpInformation_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(this.textBoxKey.Text))
                {
                    MessageBox.Show("A key must be set");
                    e.Cancel = true;
                    return;
                }

                if (this.textBoxKey.Text.Length < 8)
                {
                    MessageBox.Show("Key must be at least 8 characters.  If you are provided with less data then pad it up to 8 characters with '='s");
                    e.Cancel = true;
                    return;
                }

                // set the default settings
                int         size     = 6;
                int         step     = 30;
                OtpHashMode hashMode = OtpHashMode.Sha1;
                Key         key      = null;

                if (this.checkBoxCustomSettings.Checked)
                {
                    size = (this.radioButtonEight.Checked) ? 8 : 6;
                    if (int.TryParse(this.textBoxStep.Text, out step))
                    {
                        if (step != 30)
                        {
                            if (step <= 0)
                            {
                                this.textBoxStep.Text = "30";
                                MessageBox.Show("The time step must be a non-zero positive integer.  The standard value is 30.  If you weren't specifically given an alternate value just use 30.");
                                e.Cancel = true;
                                return;
                            }
                            else if (MessageBox.Show("You have selected a non-standard time step.  30 is the standard recommended value.  You should only proceed if you were specifically told to use this time step size.  Do you wish to proceed?", "Non-standard time step size", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                            {
                                e.Cancel = true;
                                return;
                            }
                        }
                    }
                    else
                    {
                        this.textBoxStep.Text = "30";
                        MessageBox.Show("The time step must be a non-zero positive integer.  The standard value is 30.  If you weren't specifically given an alternate value just use 30.");
                        e.Cancel = true;
                        return;
                    }
                    // need to do encoding here
                    key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(Base32.Decode(this.textBoxKey.Text.Replace(" ", string.Empty).Replace("-", string.Empty)));
                }
                else
                {
                    key = ProtectedKey.CreateProtectedKeyAndDestroyPlaintextKey(Base32.Decode(this.textBoxKey.Text.Replace(" ", string.Empty).Replace("-", string.Empty)));
                }

                // hashmode
                if (this.radioButtonSha1.Checked)
                {
                    hashMode = OtpHashMode.Sha1;
                }
                else if (this.radioButtonSha256.Checked)
                {
                    hashMode = OtpHashMode.Sha256;
                }
                else if (this.radioButtonSha512.Checked)
                {
                    hashMode = OtpHashMode.Sha512;
                }

                this.Data = new OtpAuthData()
                {
                    Key         = key,
                    Size        = size,
                    Step        = step,
                    OtpHashMode = hashMode
                };
            }
            catch
            {
                e.Cancel = true;
            }
        }
        public void KeyedHashKeyCanBeGeneratedFromAlgorithmType()
        {
            ProtectedKey generatedKey = keyedHashKeyGenerator.GenerateKey(typeof(HMACRIPEMD160), DataProtectionScope.CurrentUser);

            Assert.IsNotNull(generatedKey.EncryptedKey);
        }
        public void KeyedHashKeysCanBeGeneratedFromAlgorithmNames()
        {
            ProtectedKey generatedKey = keyedHashKeyGenerator.GenerateKey("hmacsha1", DataProtectionScope.CurrentUser);

            Assert.IsNotNull(generatedKey.EncryptedKey);
        }