/// <summary>
        /// <para>Saves a <see cref="KeyAlgorithmPair"/> to the configured file.</para>
        /// </summary>
        /// <param name="keyAlgorithmPair">
        /// <para>The <see cref="KeyAlgorithmPair"/> to store.</para>
        /// </param>
        public void Save(KeyAlgorithmPair keyAlgorithmPair)
        {
            FileKeyAlgorithmPairStorageProviderData fileKeyAlgorithmPairStorageProviderData = GetFileKeyAlgorithmPairStorageProviderData();

            using (FileStream fs = new FileStream(fileKeyAlgorithmPairStorageProviderData.Path, FileMode.Create))
            {
                if (null != fileKeyAlgorithmPairStorageProviderData.DpapiSettings)
                {
                    SerializeAndProtectFileStream(fs, keyAlgorithmPair);
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    try
                    {
                        formatter.Serialize(fs, keyAlgorithmPair);
                    }
                    catch (SerializationException e)
                    {
                        throw new ConfigurationException(e.Message, e);
                    }
                }

                fs.Flush();
            }
        }
        /// <summary>
        /// <para>Loads a <see cref="KeyAlgorithmPair"/> from the configured file.</para>
        /// </summary>
        /// <returns>
        /// <para>The deserialized <see cref="KeyAlgorithmPair"/>.</para>
        /// </returns>
        /// <exception cref="InvalidCastException">Thrown when a valid object is loaded, but it is not a <see cref="KeyAlgorithmPair"></see></exception>
        /// <exception cref="ConfigurationException">Thrown when system is unable to deserialize the stored <see cref="KeyAlgorithmPair"></see></exception>
        public KeyAlgorithmPair Load()
        {
            KeyAlgorithmPair keyAlgorithmPair = null;

            FileKeyAlgorithmPairStorageProviderData fileKeyAlgorithmPairStorageProviderData = GetFileKeyAlgorithmPairStorageProviderData();

            using (FileStream fs = new FileStream(fileKeyAlgorithmPairStorageProviderData.Path, FileMode.Open, FileAccess.Read))
            {
                if (null != fileKeyAlgorithmPairStorageProviderData.DpapiSettings)
                {
                    keyAlgorithmPair = DeserializeProtectedFileStream(fs);
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    try
                    {
                        keyAlgorithmPair = formatter.Deserialize(fs) as KeyAlgorithmPair;
                    }
                    catch (SerializationException e)
                    {
                        throw new ConfigurationException(e.Message, e);
                    }
                }
            }
            return(keyAlgorithmPair);
        }
        private KeyAlgorithmPair DeserializeProtectedFileStream(FileStream fs)
        {
            KeyAlgorithmPair keyAlgorithmPair = null;
            BinaryFormatter  formatter        = new BinaryFormatter();

            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);

            using (MemoryStream ms = new MemoryStream(UnprotectBytes(buffer)))
            {
                keyAlgorithmPair = formatter.Deserialize(ms) as KeyAlgorithmPair;
            }

            return(keyAlgorithmPair);
        }
        private void SerializeAndProtectFileStream(FileStream fs, KeyAlgorithmPair keyAlgorithmPair)
        {
            byte[] buffer = null;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, keyAlgorithmPair);
                buffer      = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Flush();
            }

            byte[] cipherBuffer = ProtectBytes(buffer);
            fs.Write(cipherBuffer, 0, cipherBuffer.Length);
        }
        /// <summary>
        /// Creates an instance.
        /// </summary>
        /// <param name="keyAlgorithmPair">The existing key algorithm pair. Pass <c>null</c> for opening an existing key algorithm pair.</param>
        /// <param name="serviceProvider">
        /// <para>The a mechanism for retrieving a service object; that is, an object that provides custom support to other objects.</para>
        /// </param>
        public FileKeyAlgorithmStorageProviderWizard(KeyAlgorithmPair keyAlgorithmPair, IServiceProvider serviceProvider)
        {
            openMode = (keyAlgorithmPair == null);
            this.keyAlgorithmPair = keyAlgorithmPair;
            this.provider = serviceProvider;

            InitializeComponent();

            if (openMode)
            {
                introLabel.Text = SR.FileKeyAlgorithmWizardLoadIntroText;
                dpapiCheckBox.Text = SR.FileKeyAlgorithmWizardDpapiLoadLabelText;
            }
            else
            {
                introLabel.Text = SR.FileKeyAlgorithmWizardSaveIntroText;
                dpapiCheckBox.Text = SR.FileKeyAlgorithmWizardDpapiSaveLabelText;
            }

            dpapiTextLabel.Text = SR.DpapiSettingsFirstRunInstructionMessage;
            dpapiTextLabel.Enabled = false;
            dpapiSettingsControl.Enabled = false;
        }
        public void ReadAndWriteToEncryptedConfiguration()
        {
            const string sectionName = "MyEncryptedConfig";

            KeyAlgorithmPair keyAlgorithmPair = new KeyAlgorithmPair();
            keyAlgorithmPair.Key = new SymmetricAlgorithmKeyCreator(typeof(RijndaelManaged).AssemblyQualifiedName).GenerateKey();
            keyAlgorithmPair.AlgorithmTypeName = typeof(RijndaelManaged).AssemblyQualifiedName;

            FileKeyAlgorithmPairStorageProvider provider = new FileKeyAlgorithmPairStorageProvider();
            provider.ConfigurationName = "FileKeyAlgorithmPairStorageProviderData";

            using (ConfigurationBuilder builder = new ConfigurationBuilder())
            {
                // change wher the file is
                RuntimeConfigurationView view = new RuntimeConfigurationView(new ConfigurationContext(new NonDisposingWrapper(builder)));

                FileKeyAlgorithmPairStorageProviderData fileData = (FileKeyAlgorithmPairStorageProviderData)view.GetKeyAlgorithmPairStorageProviderData();
                fileData.Path = Path.GetTempFileName();
                provider.Initialize(view);
                provider.Save(keyAlgorithmPair);
                builder.WriteConfiguration(sectionName, data);
                MockConfigurationData myData = (MockConfigurationData)builder.ReadConfiguration(sectionName);
                Assert.AreEqual(myData.ToString(), data.ToString());
                builder.ClearSectionCache();
                myData = (MockConfigurationData)builder.ReadConfiguration(sectionName);
                Assert.AreEqual(myData.ToString(), data.ToString());
            }
        }
        /// <summary>
        /// <para>Saves a <see cref="KeyAlgorithmPair"/> to the configured file.</para>
        /// </summary>
        /// <param name="keyAlgorithmPair">
        /// <para>The <see cref="KeyAlgorithmPair"/> to store.</para>
        /// </param>
        public void Save(KeyAlgorithmPair keyAlgorithmPair)
        {
            FileKeyAlgorithmPairStorageProviderData fileKeyAlgorithmPairStorageProviderData = GetFileKeyAlgorithmPairStorageProviderData();

            using (FileStream fs = new FileStream(fileKeyAlgorithmPairStorageProviderData.Path, FileMode.Create))
            {
                if (null != fileKeyAlgorithmPairStorageProviderData.DpapiSettings)
                {
                    SerializeAndProtectFileStream(fs, keyAlgorithmPair);
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    try
                    {
                        formatter.Serialize(fs, keyAlgorithmPair);
                    }
                    catch (SerializationException e)
                    {
                        throw new ConfigurationException(e.Message, e);
                    }
                }

                fs.Flush();
            }
        }
        private void SerializeAndProtectFileStream(FileStream fs, KeyAlgorithmPair keyAlgorithmPair)
        {
            byte[] buffer = null;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, keyAlgorithmPair);
                buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Flush();
            }

            byte[] cipherBuffer = ProtectBytes(buffer);
            fs.Write(cipherBuffer, 0, cipherBuffer.Length);
        }
 private void SaveKeyPair(KeyAlgorithmPair pair, string xmlToUse)
 {
     KeyAlgorithmStorageProviderFactory factory = new KeyAlgorithmStorageProviderFactory(CreateContext(xmlToUse));
     IKeyAlgorithmPairStorageProvider provider = factory.Create();
     provider.Save(pair);
 }
 public void ConfigurationProtectorTestWithoutDpapi()
 {
     string mySecret = "mary had a little lamb";
     RijndaelManaged myRijndael = new RijndaelManaged();
     myRijndael.GenerateKey();
     KeyAlgorithmPair pair = new KeyAlgorithmPair(myRijndael.Key, myRijndael.GetType().AssemblyQualifiedName);
     SaveKeyPair(pair, xmlString);
     ConfigurationContext context = CreateContext(xmlString);
     using (ConfigurationProtector protector = new ConfigurationProtector())
     {
         protector.Load(context, sectionName);
         byte[] inBytes = UnicodeEncoding.Unicode.GetBytes(mySecret);
         byte[] encryptedBytes = protector.Encrypt(inBytes);
         Assert.IsFalse(CryptographyUtility.CompareBytes(inBytes, encryptedBytes));
         byte[] decryptedBytes = protector.Decrypt(encryptedBytes);
         Assert.AreEqual(mySecret, UnicodeEncoding.Unicode.GetString(decryptedBytes));
     }
 }
 public void ConfigurationProtectorTestEncryptedButNoProvider()
 {
     RijndaelManaged myRijndael = new RijndaelManaged();
     myRijndael.GenerateKey();
     KeyAlgorithmPair pair = new KeyAlgorithmPair(myRijndael.Key, myRijndael.GetType().AssemblyQualifiedName);
     SaveKeyPair(pair, xmlStringWithDpapi);
     using (ConfigurationContext context = CreateContext(xmlStringNoStorageProvider))
     {
         using (ConfigurationProtector protector = new ConfigurationProtector())
         {
             protector.Load(context, sectionName);
         }
     }
 }
        private void SetDataToBeEncrypted(ConfigurationContext context)
        {
            KeyAlgorithmStorageProviderFactory factory = new KeyAlgorithmStorageProviderFactory(context);
            IKeyAlgorithmPairStorageProvider provider = factory.Create();
            keyAlgorithmPair = provider.Load();
            if (null == keyAlgorithmPair)
            {
                throw new InvalidOperationException(SR.ExceptionKeyAlgorithmPairLoad);
            }

            encrypted = true;
        }