ASP.NET の構成ファイルを暗号化する
CodeProject をチェックしていたら、ASP.NET の構成ファイルをプログラムで暗号化する方法が紹介されていました。
へぇ、と思い自分でも appSettings を暗号化しようと試してみました。
もともとの appSettings はこんな感じ。
<appSettings>
<add key="key1" value="key1's value" />
<add key="key2" value="key2's value" />
<add key="key3" value="key3's value" />
</appSettings>
そして構成ファイルを暗号化するプログラムはこんな感じ。
using System.Configuration;
using System.Web.Configuration;string provider = "RSAProtectedConfigurationProvider";
string section = "appSettings";protected void buttonEncrypt_Click(object sender, EventArgs e)
{
Configuration confg =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection(section);
if (confStrSect != null)
{
confStrSect.SectionInformation.ProtectSection(provider);
confg.Save();
}
}
これを実行すると appSettings がこんな感じで暗号化されます。
<appSettings 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#tripledes-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-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>MVZ9lJBnRj9b45wCpWVrSZgtbxLdbuMeY7StZfjMs1t1/Mx89D+XvYY4lWwRkg4kFjzP8lyVwtlZxkDrtS9NkG9kwoIQSijyNxG0qaxS+5V7VJcypPEP9f6jeewCs2DLfIUGwKy87cx+23puDGnzFQxqXcG4emF/NLPoxH2smOQ=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>BXQFUE6w8pXyzm/S7+zHZ5z/K0JgsKOof+Aiu3qPQWJFQwqRa0I+tKl1Z7rkHUFwcrpKQm2rTUOLraYbyZY0s403WHTK9KiGPQjmHSBvmz4pzaEm2OmtuBfflkXX0pCTjsxSLsbtohGOUV+ieHebSywhHxf091aCt9qvkvlzPvgN+4EMTtPJwYiOb+effVMxT3bUt3h7jFOhzRp6mVrBXarUibldfwRKWSW8QJpGRBk=</CipherValue>
</CipherData>
</EncryptedData>
</appSettings>
構成ファイルが暗号化されているのに、以下のようなプログラムで普通に値を取得できます。
protected void Button1_Click(object sender, EventArgs e)
{
textBoxKey1.Text =
System.Configuration.ConfigurationManager.AppSettings["key1"];
textBoxKey2.Text =
System.Configuration.ConfigurationManager.AppSettings["key2"];
textBoxKey3.Text =
System.Configuration.ConfigurationManager.AppSettings["key3"];
}
これはなかなかいい感じ。
復号化するには以下のようにします。
protected void buttonDecrypt_Click(object sender, EventArgs e)
{
Configuration confg =
WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection confStrSect = confg.GetSection(section);
if (confStrSect != null && confStrSect.SectionInformation.IsProtected)
{
confStrSect.SectionInformation.UnprotectSection();
confg.Save();
}
}
構成ファイルを暗号化したいときはよくあるのでこれは便利だと思いつつ、プログラムで実行するのは不便だなぁと思っていたら、aspnet_regiis コマンドで暗号化する方法がちゃんと公開されていました。
ここら辺は以下のブログで詳しく解説されています。
構成ファイルを暗号化した場合は、キーコンテナに実行ユーザーのアクセス権を aspnet_regiis コマンドで行うんですね。
スポンサーリンク
Twitter ではブログにはない、いろんな情報を発信しています。
@fnyaさんをフォロー
コメント