当前位置: 首页>>代码示例>>C#>>正文


C# ProtectedConfigurationProvider类代码示例

本文整理汇总了C#中System.Configuration.ProtectedConfigurationProvider的典型用法代码示例。如果您正苦于以下问题:C# ProtectedConfigurationProvider类的具体用法?C# ProtectedConfigurationProvider怎么用?C# ProtectedConfigurationProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ProtectedConfigurationProvider类属于System.Configuration命名空间,在下文中一共展示了ProtectedConfigurationProvider类的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Initialize

//引入命名空间
using System;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Configuration;

namespace Samples.AspNet
{
    // Shows how to create a custom protected configuration
    // provider.
    public class TripleDESProtectedConfigurationProvider :
        ProtectedConfigurationProvider
    {

        private TripleDESCryptoServiceProvider des =
            new TripleDESCryptoServiceProvider();

        private string pKeyFilePath;
        private string pName;

        // Gets the path of the file
        // containing the key used to
        // encryption or decryption.
        public string KeyFilePath
        {
            get { return pKeyFilePath; }
        }

        // Gets the provider name.
        public override string Name
        {
            get { return pName; }
        }

        // Performs provider initialization.
        public override void Initialize(string name,
            NameValueCollection config)
        {
            pName = name;
            pKeyFilePath = config["keyContainerName"];
            ReadKey(KeyFilePath);
        }

        // Performs encryption.
        public override XmlNode Encrypt(XmlNode node)
        {
            string encryptedData = EncryptString(node.OuterXml);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml("<EncryptedData>" +
                encryptedData + "</EncryptedData>");

            return xmlDoc.DocumentElement;
        }

        // Performs decryption.
        public override XmlNode Decrypt(XmlNode encryptedNode)
        {
            string decryptedData =
                DecryptString(encryptedNode.InnerText);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(decryptedData);

            return xmlDoc.DocumentElement;
        }

        // Encrypts a configuration section and returns 
        // the encrypted XML as a string.
        private string EncryptString(string encryptValue)
        {
            byte[] valBytes =
                Encoding.Unicode.GetBytes(encryptValue);

            ICryptoTransform transform = des.CreateEncryptor();

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
                transform, CryptoStreamMode.Write);
            cs.Write(valBytes, 0, valBytes.Length);
            cs.FlushFinalBlock();
            byte[] returnBytes = ms.ToArray();
            cs.Close();

            return Convert.ToBase64String(returnBytes);
        }

        // Decrypts an encrypted configuration section and 
        // returns the unencrypted XML as a string.
        private string DecryptString(string encryptedValue)
        {
            byte[] valBytes =
                Convert.FromBase64String(encryptedValue);

            ICryptoTransform transform = des.CreateDecryptor();

            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms,
                transform, CryptoStreamMode.Write);
            cs.Write(valBytes, 0, valBytes.Length);
            cs.FlushFinalBlock();
            byte[] returnBytes = ms.ToArray();
            cs.Close();

            return Encoding.Unicode.GetString(returnBytes);
        }

        // Generates a new TripleDES key and vector and 
        // writes them to the supplied file path.
        public void CreateKey(string filePath)
        {
            des.GenerateKey();
            des.GenerateIV();

            StreamWriter sw = new StreamWriter(filePath, false);
            sw.WriteLine(ByteToHex(des.Key));
            sw.WriteLine(ByteToHex(des.IV));
            sw.Close();
        }

        // Reads in the TripleDES key and vector from 
        // the supplied file path and sets the Key 
        // and IV properties of the 
        // TripleDESCryptoServiceProvider.
        private void ReadKey(string filePath)
        {
            StreamReader sr = new StreamReader(filePath);
            string keyValue = sr.ReadLine();
            string ivValue = sr.ReadLine();
            des.Key = HexToByte(keyValue);
            des.IV = HexToByte(ivValue);
        }

        // Converts a byte array to a hexadecimal string.
        private string ByteToHex(byte[] byteArray)
        {
            string outString = "";

            foreach (Byte b in byteArray)
                outString += b.ToString("X2");

            return outString;
        }

        // Converts a hexadecimal string to a byte array.
        private byte[] HexToByte(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] =
                    Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
    }
}
开发者ID:.NET开发者,项目名称:System.Configuration,代码行数:161,代码来源:ProtectedConfigurationProvider

示例2: ProtectConfiguration

//引入命名空间
using System;
using System.Configuration;
using Samples.AspNet.Configuration;

namespace Samples.AspNet.Configuration
{

    // Show how to use a custom protected configuration
    // provider.
    public class TestingProtectedConfigurationProvider
    {

        // Protect the connectionStrings section.
        private static void ProtectConfiguration()
        {

            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Define the provider name.
            string provider =
                "TripleDESProtectedConfigurationProvider";

            // Get the section to protect.
            ConfigurationSection connStrings =
                config.ConnectionStrings;

            if (connStrings != null)
            {
                if (!connStrings.SectionInformation.IsProtected)
                {
                    if (!connStrings.ElementInformation.IsLocked)
                    {
                        // Protect the section.
                        connStrings.SectionInformation.ProtectSection(provider);

                        connStrings.SectionInformation.ForceSave = true;
                        config.Save(ConfigurationSaveMode.Full);

                        Console.WriteLine("Section {0} is now protected by {1}",
                            connStrings.SectionInformation.Name,
                            connStrings.SectionInformation.ProtectionProvider.Name);
                    }
                    else
                        Console.WriteLine(
                             "Can't protect, section {0} is locked",
                             connStrings.SectionInformation.Name);
                }
                else
                    Console.WriteLine(
                        "Section {0} is already protected by {1}",
                        connStrings.SectionInformation.Name,
                        connStrings.SectionInformation.ProtectionProvider.Name);
            }
            else
                Console.WriteLine("Can't get the section {0}",
                    connStrings.SectionInformation.Name);
        }

        // Unprotect the connectionStrings section.
        private static void UnProtectConfiguration()
        {

            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Get the section to unprotect.
            ConfigurationSection connStrings =
                config.ConnectionStrings;

            if (connStrings != null)
            {
                if (connStrings.SectionInformation.IsProtected)
                {
                    if (!connStrings.ElementInformation.IsLocked)
                    {
                        // Unprotect the section.
                        connStrings.SectionInformation.UnprotectSection();

                        connStrings.SectionInformation.ForceSave = true;
                        config.Save(ConfigurationSaveMode.Full);

                        Console.WriteLine("Section {0} is now unprotected.",
                            connStrings.SectionInformation.Name);
                    }
                    else
                        Console.WriteLine(
                             "Can't unprotect, section {0} is locked",
                             connStrings.SectionInformation.Name);
                }
                else
                    Console.WriteLine(
                        "Section {0} is already unprotected.",
                        connStrings.SectionInformation.Name);
            }
            else
                Console.WriteLine("Can't get the section {0}",
                    connStrings.SectionInformation.Name);
        }

        public static void Main(string[] args)
        {

            string selection = string.Empty;

            if (args.Length == 0)
            {
                Console.WriteLine(
                    "Select createkey, protect or unprotect");
                return;
            }

            selection = args[0].ToLower();

            switch (selection)
            {

                // Create the key to use during 
                // encryption/decryption.
                case "createkey":
                    string keyContainer = 
                        "pcKey.txt";

                    // Instantiate the custom provider.
                    TripleDESProtectedConfigurationProvider 
                        provider =
                        new TripleDESProtectedConfigurationProvider();

                    // Create the encryption/decryption key.
                    provider.CreateKey(keyContainer);

                    Console.WriteLine(
                        "New TripleDES key created in {0}",
                        keyContainer);
                    break;

                case "protect":
                    ProtectConfiguration();
                    break;

                case "unprotect":
                    UnProtectConfiguration();
                    break;

                default:
                    Console.WriteLine("Unknown selection");
                    break;
            }

            Console.Read();
        }
    }
}
开发者ID:.NET开发者,项目名称:System.Configuration,代码行数:158,代码来源:ProtectedConfigurationProvider


注:本文中的System.Configuration.ProtectedConfigurationProvider类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。