摘要:.NET aspnet_regiis.exe加密
為了不讓pwd明碼顯示於app.config中,寫支程式,利用.NET Framework本身的功能進行加密動作
路徑為 C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe
不過經加密後的config檔只能用在同樣一台電腦執行,換一台就不能用了。
且.NET Framework這支程式只能對檔名為web.config才能加密
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Configuration;
namespace ConnStrEnc
{
class Program
{
static void fileBackup(string srcFile)
{
string srcFName = srcFile.Substring(srcFile.LastIndexOf("\\") + 1);
int ind = srcFName.LastIndexOf(".");
string destFName = srcFName.Substring(0, ind) + "_bak" + srcFName.Substring(ind);
string destFile = srcFile.Replace(srcFName, destFName);
System.IO.File.Copy(srcFile, destFile, true);
}
static void fileEnc(string srcFile, string str)
{
// File Backup
fileBackup(srcFile);
// FileName Changed
int ind = srcFile.LastIndexOf("\\");
string srcPath = srcFile.Substring(0,ind);
string srcFName = srcFile.Substring(ind + 1);
string destFile = srcFile.Replace(srcFName, "web.config");
System.IO.File.Move(srcFile, destFile);
System.Console.WriteLine("str " + str);
System.Console.WriteLine("srcPath " + srcPath);
// Process aspnet_regiis
try
{
Process aspnet_regiis = new Process();
aspnet_regiis.StartInfo.FileName = "C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\aspnet_regiis.exe";
aspnet_regiis.StartInfo.Arguments = "-pef " + str + " " + srcPath;
aspnet_regiis.Start();
aspnet_regiis.WaitForExit();
}
catch(Exception e)
{
Console.WriteLine("Exception source: {0}", e.Source);
}
// FileName turn back
System.IO.File.Move(destFile, srcFile);
}
static void listRead(string listFile)
{
try
{
string line;
char[] delimiterChars = {'\t'};
System.IO.StreamReader file = new System.IO.StreamReader(listFile);
while ((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
string[] fs = line.Split(delimiterChars);
System.Console.WriteLine("fs[0] = " + fs[0]);
System.Console.WriteLine("fs[1] = " + fs[1]);
fileEnc(fs[0],fs[1]);
}
file.Close();
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
listRead("D:\\Cedar\\trans\\list.txt");
//fileBackup("D:\\Cedar\\trans\\FILENET.exe.config");
//fileEnc("D:\\Cedar\\trans\\FILENET.exe.config", "connectionStrings");
}
}
}
list.txt
D:\Cedar\trans\FILENET.exe.config connectionStrings
D:\Cedar\trans\FCC.exe.config connectionStrings
<configuration>
</appSettings>
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="MMASConnectionString" connectionString="Data Source=192.168.XX.XXX,1803;Initial Catalog=BSNS;UID=timliao;PWD=timliao;"
providerName="" />
</connectionStrings>
</configuration>