چگونه Connection String را امن و رمزنگاری کنیم؟ در این مطلب نحوه رمزنگاری decrypt و encrypt کردن رشته اتصال به بانک اطلاعاتی ConnectionString های موجود در App Config را خواهم گفت
مجموعه دوره آموزش برنامه نویسی - مقدماتی تا پیشرفته
رمز نگاری توسط Method ای که در زیر آمده است انجام میشود که این عملیات دو پارامتر دریافت میکند یکی آدرس فایل Config و دیگری یک boolean هست نیاز به ادامه نیست فقط به همین نکته کوناه بسنده میکنم که مقدار Boolean میتونه یا False باشه یا True که تعیین میکنه باید decrypt انجام بشه یا encrypt.
public static void EncryptConnectionString(bool encrypt, string fileName)
{
Configuration configuration = null;
try
{
// Open the configuration file and retrieve the connectionStrings section.
configuration = ConfigurationManager.OpenExeConfiguration(fileName);
ConnectionStringsSection configSection = configuration.GetSection("connectionStrings") as ConnectionStringsSection;
if ((!(configSection.ElementInformation.IsLocked)) && (!(configSection.SectionInformation.IsLocked)))
{
if (encrypt && !configSection.SectionInformation.IsProtected)
{
//this line will encrypt the file
configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
}
if (!encrypt && configSection.SectionInformation.IsProtected)//encrypt is true so encrypt
{
//this line will decrypt the file.
configSection.SectionInformation.UnprotectSection();
}
//re-save the configuration file section
configSection.SectionInformation.ForceSave = true;
// Save the current configuration
configuration.Save();
Process.Start("notepad.exe", configuration.FilePath);
//configFile.FilePath
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
حالا که با این کد آشنا شدیم میتونیم بگیم رشته اتصال قبل از رمز نگاری به چه صورتی هست:
<connectionStrings>
<add name="SecurePassDataBase" connectionString="Data Source=D-6058;
Initial Catalog=DEMO_Test;User ID=sysdba;Password=xxxxxx" />
</connectionStrings>
رشته اتصال بعد از رمز نگاری هم به صورت زیر هست.
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAATeylFe/
xsUiVdcZvovEYDwQAAAACAAAAAAADZgAAwAAAABAAAABZsoaKP62hL85wpS+O3+
znAAAAAASAAACgAAAAEAAAAHZ5NcKcDcWuEVDKyU4mz7J4AQAAAILD3fmIimyY2rkEkAdAtRn0dh9tI7+
Y5+ILciikoSd/y2myUS88vJ59pIf82vOLk/0UwKL8TnHEaFTeX7SJ5par6pW7Pyhu4kKTEMyMUQsZX/
h8RjNOnt+Q/kZIdqF2YWxFUP0RF3GWirvMNWS3do7IE0WaJ1W3wL+HhalglmKURWIGHsvJlybl+
EGI8crPnli0W/yMN+fR0P/ndaTY87kR4+0gvKDWzZ/dMh8E7ZtodFzTQ4pjpl5YyRHH/
Tc3oFUtimCnzXvCVT4ykK6NEQfPiPc5KJW6ajTEEGOrAXTnr9HF2wCRekE3WUVPYkeHRTjtuf
2hUyvYx4eoGeOIAzFFXxY1GzZqhl8YaHlukZagiTVbfXA6Wh+K0dsAiOPz+wbCT92/
blgsdkoKSMy8vRqFxAhX8HoW6KbJhsBPOvv36iBr1RecCpzUxWrVssS+wi/JclVfVs0nYb/
pFidcJwhuwBsS6IzvV1tgrk8F9CUor+6DYHd/ABQAAABZjFi30hPRmKj+pvxFzjeNH+
Dhhg==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>