ASP.NET Web.Config 連線字串加密

最近在整理以前練習的官方範例,想到 Web.Config 的連線字串應該要做保護。查了下資料寫個筆記,避免之後遇到上古時代的專案手忙腳亂。

aspnet_regiis 位置

預設在 %systemroot%\Microsoft.NET\Framework\{versionNumber} 底下可以找到 aspnet_regiis.exe

加密

  • 加密前

    1
    2
    3
    4
    5
    <connectionStrings>
    <add name="NorthwindEntities"
    connectionString="metadata=res://*/NorthwindModels.csdl|res://*/NorthwindModels.ssdl|res://*/NorthwindModels.msl;provider=System.Data.SqlClient;provider connection string='data source=&quot;localhost, 1433&quot;;initial catalog=Northwind;persist security info=True;user id=********;password=**********;pooling=False;multipleactiveresultsets=False;connect timeout=60;trustservercertificate=False;App=EntityFramework'"
    providerName="System.Data.EntityClient" />
    </connectionStrings>
  • 加密指令

    1
    2
    # aspnet_regiis -pef [section] [path]
    .\aspnet_regiis.exe -pef "connectionStrings" "D:\Repository\SampleApplication"
  • 加密後

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
    xmlns="http://www.w3.org/2001/04/xmlenc#">
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
    <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
    <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
    <KeyName>Rsa Key</KeyName>
    </KeyInfo>
    <CipherData>
    <CipherValue>.....</CipherValue>
    </CipherData>
    </EncryptedKey>
    </KeyInfo>
    <CipherData>
    <CipherValue>......</CipherValue>
    </CipherData>
    </EncryptedData>
    </connectionStrings>

解密

1
2
# aspnet_regiis -pdf [section] [path]
.\aspnet_regiis.exe -pdf "connectionStrings" "D:\Repository\SampleApplication"

延伸閱讀

web.config連線字串加密工具

參考連結

  1. How to: Secure Connection Strings When Using Data Source Controls