はじめに
C#アプリケーション(コンソールやデスクトップ等)では必ずapp.configが存在しています(利用していない場合も含む)。
このapp.configには設定情報はもちろんのこと、パスワード情報などセキュリティリスクが高まるような情報を設定するケースも多いかと思います。
本項では、このapp.configに記載するappSettingsセクションやconnectionStringsセクションの情報を暗号化/復号化する方法の備忘録です。
暗号化
暗号化方法はDPAPIまたはRSAの2つの方法があります。
// 利用するライブラリ
// System.Net.Configuration
string baseFilePath = @"C:¥work¥app.config";
string outPath = @"C:¥work¥app_out.config";
// 暗号化対象のファイルをコピーする
// (元の暗号化前のファイルも残す場合)
File.Copy(baseFilePath, outPath);
ExeConfigurationFileMap exeFileMap = new ExeConfigurationFileMap { ExeConfigFilename = outPath };
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);
// appSettingsセクション情報の取得
AppSettinsSection ass = config.GetSection("appSettings") as AppSettingsSection;
// appSettins暗号化処理
if (ass.SectionInformation.IsProtected == false)
{
// DPAPIによる暗号化
ass.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
// RSAによる暗号化
ass.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
}
// connectionStringsセクション情報の取得
ConnectionStringsSection css = config.GetSection("connectionStrings") as ConnectionStringsSection;
// connectionStrings暗号化処理
if (css.SectionInformation.IsProtected == false)
{
// DPAPIによる暗号化
css.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
// RSAによる暗号化
css.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
}
config.Save();
DPAPIにて暗号化した場合は、別コンピュータにて動作させるとエラーが発生します。
DPAPIではコンピュータレベルとユーザレベルを設定することができ、デフォルトではコンピュータレベルとなります。
ユーザレベルを設定する場合はapp.configにconfigProtectedDataセクションを追加し、その設定したプロバイダ名を呼び出す
// 例:connectionStringsの部分を変更
css.SectionInformation.ProtectSection("UserDpapiProtectionConfigurationProvider");
上記で、ユーザレベルでの暗号化が可能となります。
また、RSAによる暗号化により作成されたKeyについては、下記ディレクトリに保存されています。
- ユーザレベル
- ¥Documents and Settings(UserName)¥Application Data¥Microsoft¥Crypto¥RSA
- コンピュータレベル
- ¥Documents and Settings¥All Users¥Application Data¥Microsoft¥Crypto¥RSA¥MachineKyes
複合化
複合化する場合は、とても簡単です。
UnprotectionSectionを利用します。
// セクション情報などの取得については省略
// appSettinsの場合はass、connectionStringsの場合はcssとしています。
if(ass.SectionInformation.IsProtected == true)
{
ass.SectionInformation.UnprotectSection();
}
if(css.SectionInformation.IsProtected == true)
{
css.SectionInformation.UnprotectSection();
}
config.Save();
最後に
いかがでしたでしょうか。
セキュリティを強固にするためにアプリケーション設定ファイルを暗号化することは重要だと考えています。
web.configも同様に対応可能です。
是非上記方法を考えてみてください。