加密数据库中的所有存储过程
一个快速的 C# 控制台应用程序,用于加密数据库中的所有存储过程
引言
如果您决定需要保护您的 SQL 存储过程,并认为加密是一个好主意,请务必小心!!!
在没有存储过程的备份文件或某种源代码控制的情况下,不应加密数据库存储过程。 我这样说是因为,一旦它们被加密,就无法恢复。 (是的,有一些第三方工具可以解密您的代码,但为什么要费这么大劲。)
我开发了这个技巧,因为我的公司需要将应用程序托管在不同的服务器上,并且我们担心我们的代码被泄露。 因此,为了交付数据库,我们决定加密所有存储过程。 编写了超过一百个过程后,我不想打开每个过程并将 'WITH ENCRYPTION
' 粘贴到每个存储过程中。 (对于那些不知道如何加密的人,请参阅 如何保护我的存储过程代码[^])。 因此,我决定编写自己的一个小 C# 应用程序来执行相同的操作。
这个应用程序是一个使用 Visual Studio 2005 和 SQL Server 2005 创建的控制台应用程序。 输入参数是数据库名称、服务器地址、数据库用户名和密码。 一旦您能够提供这些详细信息,您就可以准备加密所有存储过程了。
我将应用程序的代码原样放在这里。 为了使这段代码工作,您需要向应用程序添加一个 "Microsft.SQlserver.SMO
" 引用,以便可以访问 "Database
" 和 "StoredProcedure
" 等类。
在您执行此操作之前,请务必备份!!!
//Connect to the local, default instance of SQL Server.
string DB = "";
ServerConnection objServerCOnnection = new ServerConnection();
objServerCOnnection.LoginSecure = false;
Console.WriteLine("Enter name or IP Address of the Database Server.");
objServerCOnnection.ServerInstance = Console.ReadLine();
Console.WriteLine("Enter name of the Database");
DB = Console.ReadLine();
Console.WriteLine("Enter user id");
objServerCOnnection.Login = Console.ReadLine();
Console.WriteLine("Enter Password");
objServerCOnnection.Password = Console.ReadLine();
Console.WriteLine(" ");
Server srv = new Server();
try // Check to see if server connection details are ok.
{
srv = new Server(objServerCOnnection);
if (srv == null)
{
Console.WriteLine("Server details entered are wrong,"
+ " Please restart the application");
Console.ReadLine();
System.Environment.Exit(System.Environment.ExitCode);
}
}
catch
{
Console.WriteLine("Server details entered are wrong,"
+ " Please restart the application");
Console.ReadLine();
System.Environment.Exit(System.Environment.ExitCode);
}
Database db = new Database();
try // Check to see if database exists.
{
db = srv.Databases[DB];
if (db == null)
{
Console.WriteLine("Database does not exist on the current server,"
+ " Please restart the application");
Console.ReadLine();
System.Environment.Exit(System.Environment.ExitCode);
}
}
catch
{
Console.WriteLine("Database does not exist on the current server,"
+ " Please restart the application");
Console.ReadLine();
System.Environment.Exit(System.Environment.ExitCode);
}
string allSP = "";
for (int i = 0; i < db.StoredProcedures.Count; i++)
{
//Define a StoredProcedure object variable by supplying the parent database
//and name arguments in the constructor.
StoredProcedure sp;
sp = new StoredProcedure();
sp = db.StoredProcedures[i];
if (!sp.IsSystemObject)// Exclude System stored procedures
{
if (!sp.IsEncrypted) // Exclude already encrypted stored procedures
{
string text = "";// = sp.TextBody;
sp.TextMode = false;
sp.IsEncrypted = true;
sp.TextMode = true;
sp.Alter();
Console.WriteLine(sp.Name); // display name of the encrypted SP.
sp = null;
text = null;
}
}
}
注意: 请留下关于这段代码的反馈。 积极的、消极的…… 没关系,如果它对您有帮助,欢迎!!
这是我在 CodeProject 上的第一篇帖子。