ASP.NET Encrypt and Decrypt

背景

在程序或服務(wù)開(kāi)發(fā)過(guò)程中,我們通常會(huì)把一些程序需要用到的常量數(shù)據(jù)配置在web.config或app.config文件中募疮,通常配置到這些文件中的Key與Value都是明文的涣易,但有時(shí)候我們并不希望這些配置讓他人知道蚯嫌。
在這種情況下贬蛙,我們可以使用ASP.NET Encrypt和Decrypt來(lái)對(duì)配置文件進(jìn)行加密长搀,不影響程序使用蹂季,但又不被他人知道配置的具體內(nèi)容冕广。


環(huán)境

  1. Windonw 7 / Windows Server 2008
  2. .Net Framework 4.0
  3. IIS

以上環(huán)境準(zhǔn)備好后,在搭建好的IIS上創(chuàng)建三個(gè)站點(diǎn) WebSite1, WebSite2, WebSite3


工具

  1. asp.net_regiis.exe
  2. vs 2010 tool
  3. sn.exe
  4. gacutil.exe

asp.net_regiis.exe位于路徑C:\Windows\Microsoft.NET\Framework64\v4.0.30319
使用管理員身份運(yùn)行cmd.exe
Start --> All Programs --> Microsoft Visual Studio 2010 --> Visual Studio Tools --> Visual Studio x64 Win64 Command Prompt (2010)(run as administrator)
sn, gacutil 在VS 2010 tool中可直接使用


Providers in .NET Framework

  • DpapiProtectedConfigurationProvider
    uses the Windows Data Protected API(DPAPI) to encrypt and Decrypt data.

  • RsaProtectedConfigurationProvider
    useed the RSA encryption algorithm to encrypt and Decrypt data.

Providers means Protected configuration Providers


Machine-Level and User-Level

Machine-Level

available to all users
Machine-level 的Key對(duì)所有管理員用戶(hù)有效果偿洁,但也受ACLs的約束

User-Level

available only to the user that created the key container.
stored with the Windonw user profile for a particular user
userd to encrypt and decrypt information for applications that run under that specific user identity.
user-level 的Key是與用戶(hù)賬號(hào)綁定的撒汉,用戶(hù)被刪除時(shí),key也被刪除

這里所講的avalliable是指能夠加密和解密


Tool and Parameters

Tool

asp.net_regiis.exe

encrypt parameters

-pe the name of the configuraiton element to be encrypt
-app identity the application for which the web.config file will be encrypted
-site identity which web site the application is a part of
-prov identity the name of the ProtectedConfigurationProvider that will preform the encryption and decryption.
pe, app 是必須要指定的值
site默認(rèn)值為1, prov默認(rèn)使用defaultProvider

decrypt parameters

-pd the name of the configuration element to be decrypted.
-app identify the application for which the web.config file will be encrypted
-site identify which Web site the application is a part of
-prov not need to specify
在解密時(shí)不需要使用prov來(lái)指定ProtectedConfigurationProvider涕滋,because that information is read from the configProtectionProvider attribute of the protected configuration section.


Encrypting Website’s Web.config

在VS Tool中輸入以下命令

aspnet_regiis -pef "connectionStrings" E:\webSite1

aspnet_regiis -pe "connectionStrings" -app "/WebSite1" -site "WebSite1"

需要為WebSite1添加虛擬目錄

aspnet_regiss -pe "connectionStrings" -app "/WebSite1" -site "WebSite1" -prov DataProtectionConfigurationProvider

需要為WebSite1添加虛擬目錄睬辐,指定Provider


解密

aspnet_regiis -pd "connectionStrings" -app "/WebSite1" -site "WebSite1"


Create a RSA Key Container

Tool

aspnet_regiis

Parameters

-pc : the name of the key container used by the RsaProtectedConfigurationProvider specified in the configProtectedData section of web.config file
-exp : ensure that RSA key container can be exported

Web.config的配置

<configProtectedData>
    <providers>
        <add name="CustomerProvider" keyContainerName="SampleKeys" useMachineContainer="true" description="Users RsaCryptoSErviceProvider to encrypt and decrypt" type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=4.0.0.0, Cultuer=neutral, PublicKeyToken=b03f5f7f11d50a3a">
    </providers>
</configProtectedData>

以上配置中的KeyContainerName="true",表示使用Machine-level, false表示使用user-level
加密時(shí)使用以下命令

aspnet_regiis -pe "connectionStrings" -app "/WebSite2" -site "WebSite2" -prov "CustomeProvider"

Exporting a RSA Key Container

使用命令

aspnet_regiis -px "SampleKeys" E:\MachineSmapleKey.xml -pri

Importing a RSA Key Container

aspnet_regiis -pi "MyKeys" keys.xml -pku

Deleting a RSA Key Container

aspnet_regiis -pz "MyKeys"


Custome Provider Type

Implementing a Protected Configuration Provider

  • Algorithm
    an algorithm other than those available with the RSA or DPAPI providers
  • Required Classes
    ProtectedConfigurationProvider class from the System.Configuration namespace
    ProviderBase class from the System.Configuration.Provider namespace
  • Required Members
    Initialize method (from ProviderBase)
    Encrypt method (from ProtectedConfigurationProvider)
    Decrypt method (from ProtectedConfigurationProvider)

Build Protected Configuration Provider

  • Generate a strong-name key pair

sn -k keys.snk

  • Create a program file named TripleDESProtectedConfigurationProvider
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 AA.BB.ProtectedConfiguration
{

  public class TripleDESProtectedConfigurationProvider : ProtectedConfigurationProvider
  {

    private TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

    private string pKeyFilePath;
    private string pName;

    public string KeyFilePath
    {
      get { return pKeyFilePath; }
    }


    //
    // ProviderBase.Name
    //

    public override string Name
    {
      get { return pName; }
    }


    //
    // ProviderBase.Initialize
    //

    public override void Initialize(string name, NameValueCollection config)
    {
      pName = name;
      pKeyFilePath = config["keyFilePath"];
      ReadKey(KeyFilePath);
    }


    //
    // ProtectedConfigurationProvider.Encrypt
    //

    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;
    }


    //
    // ProtectedConfigurationProvider.Decrypt
    //

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

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

      return xmlDoc.DocumentElement;
    }


    //
    // EncryptString
    //    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);
    }


    //
    // DecryptString
    //    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);
    }

    //
    // CreateKey
    //    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();
    }


    //
    // ReadKey
    //    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);
    }


    //
    // ByteToHex
    //    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;
    }

    //
    // HexToByte
    //    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;
    }

  }
}
  • Compile the code and assign the resulting assembly with the strong-name key

csc /out:TripleDESProtectedConfigurationProvider.dll /t:library TripleDESProtectedConfigurationProvider.cs /r:System.Configuration.dll /keyfile:keys.snk

  • Install the assembly in the GAC(global assembly cach)

    gacutil -i TripleDESProtectedConfigurationProvider.dll


Use a Custom Provider type

  • Generate Key File

    CreateKey.exe E:\ASP\Keys.txt

  • Modify the configProtectedData Section of the Web.config

<configProtectedData>
    <providers>
        <add name="SampleProvider"  useMachineContainer="true" type="AA.BB.TripleDESProtectedConfigurationProvider TripleDESProtectedConfigurationProvider  Version=0.0.0.0, Cultuer=neutral  PublicKeyToken=b06675f7f11d50a3a",description="Users RsaCryptoSErviceProvider to encrypt and decrypt" keyFilePath="E:\ASP\Key" >    
    </providers>
</configProtectedData>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子溯饵,更是在濱河造成了極大的恐慌侵俗,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件丰刊,死亡現(xiàn)場(chǎng)離奇詭異隘谣,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)啄巧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)寻歧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人秩仆,你說(shuō)我怎么就攤上這事码泛。” “怎么了澄耍?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵噪珊,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我齐莲,道長(zhǎng)痢站,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任选酗,我火速辦了婚禮瑟押,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘星掰。我一直安慰自己,他們只是感情好嫩舟,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布氢烘。 她就那樣靜靜地躺著,像睡著了一般家厌。 火紅的嫁衣襯著肌膚如雪播玖。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,929評(píng)論 1 290
  • 那天饭于,我揣著相機(jī)與錄音蜀踏,去河邊找鬼。 笑死掰吕,一個(gè)胖子當(dāng)著我的面吹牛果覆,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播殖熟,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼局待,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起钳榨,我...
    開(kāi)封第一講書(shū)人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤舰罚,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后薛耻,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體营罢,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年饼齿,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了饲漾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡候醒,死狀恐怖能颁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情倒淫,我是刑警寧澤伙菊,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站敌土,受9級(jí)特大地震影響镜硕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜返干,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一兴枯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧矩欠,春花似錦财剖、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至乳蓄,卻和暖如春咪橙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背虚倒。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工美侦, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人魂奥。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓菠剩,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親捧弃。 傳聞我的和親對(duì)象是個(gè)殘疾皇子赠叼,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容