gpt4 book ai didi

c# 如何加密 SQL Server 连接字符串?

转载 作者:行者123 更新时间:2023-12-02 04:11:10 26 4
gpt4 key购买 nike

我想创建一个连接到 SQL Server 并具有完全访问权限的客户端。

如何让其他人看不到 SQL Server 的连接字符串并通过其他数据库编辑器访问它?我知道 .NET 应用程序可以被反编译,所以我担心我的服务器。

最佳答案

这是一个简单连接字符串加密/解密机制的不太安全引用实现。

首先,使用 Base64 编码方案对连接字符串进行编码。

未编码的连接字符串:

server=localhost\SQLEXPRESS2012;database=testdb;uid=testuser;pwd=supersecret

Base64 编码连接字符串:

c2VydmVyPWxvY2FsaG9zdFxTUUxFWFBSRVNTMjAxMjtkYXRhYmFzZT10ZXN0ZGI7dWlkPXRlc3R1c2VyO3B3ZD1zdXBlcnNlY3JldA==

此后,App.config 文件中的相应行应如下所示。

<add name="TestDb" connectionString="c2VydmVyPWxvY2FsaG9zdFxTUUxFWFBSRVNTMjAxMjtkYXRhYmFzZT10ZXN0ZGI7dWlkPXRlc3R1c2VyO3B3ZD1zdXBlcnNlY3JldA==" providerName="System.Data.SqlClient" />

最后,修改您的 DbContext 以便能够使用编码的连接字符串创建数据库连接。

using System;
using System.Configuration;
using System.Data.Common;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Text;

namespace TestApp
{
public class TestDb : DbContext
{
public TestDb() : base(CreateConnection("TestDb"), true)
{
}

static DbConnection CreateConnection(string dbName)
{
string encodedCs = ConfigurationManager.ConnectionStrings[dbName].ConnectionString;
string decodedCs = Encoding.UTF8.GetString(Convert.FromBase64String(encodedCs));
return new SqlConnection(decodedCs);
}
}
}

正如您所注意到的,此实现使用 Base64 编码方案,如果最终用户知道自己在做什么,则可以轻松逆转该方案。

关于c# 如何加密 SQL Server 连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com