Tôi cần trợ giúp về mã hóa chuỗi kết nối trong app.config
và lưu nó ở đó và giải mã nó để sử dụng.C#: Cần trợ giúp về mã hóa chuỗi kết nối trong app.config và lưu nó ở đó và giải mã nó và sử dụng?
Q
C#: Cần trợ giúp về mã hóa chuỗi kết nối trong app.config và lưu nó ở đó và giải mã nó và sử dụng?
5
A
Trả lời
2
Bạn có thể sử dụng aspnet_regiis.exe -pef
cho điều đó.
Xem Encrypting the connection string in ASP.NET V2.0 và Encrypting Web.Config Values in ASP.NET 2.0 bài viết để được giải thích thêm.
0
Ngoài nhận xét của @ Li0liQ, bạn có thể sử dụng chương trình dòng lệnh đi kèm với .NET Framework 2.0+ aspnet_regiis
. Kiểm tra tài liệu MSDN here
2
Nếu bạn muốn bảo vệ theo cách thủ công, bạn có thể sử dụng lớp ProtectedData
. Một số mã:
class ConnectionStringProtector
{
readonly byte[] _salt = new byte[] { 1, 2, 3, 4, 5, 6 }; // Random values
readonly Encoding _encoding = Encoding.Unicode;
readonly DataProtectionScope _scope = DataProtectionScope.LocalMachine;
public string Unprotect(string str)
{
var protectedData = Convert.FromBase64String(str);
var unprotected = ProtectedData.Unprotect(protectedData, _salt, _scope);
return _encoding.GetString(unprotected);
}
public string Protect(string unprotectedString)
{
var unprotected = _encoding.GetBytes(unprotectedString);
var protectedData = ProtectedData.Protect(unprotected, _salt, _scope);
return Convert.ToBase64String(protectedData);
}
}
đây là một thử nghiệm đơn giản:
static void Main(string[] args)
{
var originalConnectionString = "original string";
var protector = new ConnectionStringProtector();
var protectedString = protector.Protect(originalConnectionString);
Console.WriteLine(protectedString);
Console.WriteLine();
var unprotectedConnectionString = protector.Unprotect(protectedString);
Console.WriteLine(unprotectedConnectionString);
Console.WriteLine("Press ENTER to finish");
Console.ReadLine();
}
Một thực hiện tham chiếu được mô tả [ở đây] (https://stackoverflow.com/a/46405204/421695). – sefakeles