加密数据库用户&密码

时间:2013-02-26 13:33:27

标签: c# nlog

Nlog能够将日志写入数据库 为此,您需要提供用户/传递nlog配置或Web配置。

有没有办法加密它?

1 个答案:

答案 0 :(得分:1)

您可能需要查看Encrypting Passwords in a .NET app.config File

将以下类添加到项目中:

class Encryption
{
    static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("Add some entropy");

    public static string EncryptString(System.Security.SecureString input)
    {
        byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
            System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
            entropy,
            System.Security.Cryptography.DataProtectionScope.CurrentUser);
        return Convert.ToBase64String(encryptedData);
    }

    public static SecureString DecryptString(string encryptedData)
    {
        try
        {
            byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
                Convert.FromBase64String(encryptedData),
                entropy,
                System.Security.Cryptography.DataProtectionScope.CurrentUser);
            return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
        }
        catch
        {
            return new SecureString();
        }
    }

    public static SecureString ToSecureString(string input)
    {
        SecureString secure = new SecureString();
        foreach (char c in input)
        {
            secure.AppendChar(c);
        }
        secure.MakeReadOnly();
        return secure;
    }

    public static string ToInsecureString(SecureString input)
    {
        string returnValue = string.Empty;
        IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
        try
        {
            returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
        }
        return returnValue;
    }
}

使用以下语法获取加密密码字符串:

var encryptedPassword = Encryption.EncryptString(
    Encryption.ToSecureString("yourPassword"));

在配置文件中,确保将clear password替换为数据库目标encryptedPassword的内容:

<target xsi:type="Database"
  name="d1"
  dbUserName="log"
  dbProvider="System.Data.SqlClient"
  dbDatabase="NLog"
  dbPassword="AQAAA... + the rest of the encryptedPassword string"
  dbHost="TheLogServer"
  commandText="INSERT INTO [LOG] VALUES (@p)">
  <parameter layout="${longdate}|${level:uppercase=true}|${logger}|${message}" name="p" />
</target>

创建一个方法,该方法将替换当前类记录器的DBPassword,并将使用解密的密码返回记录器:

static Logger logger = GetLogger();

private static Logger GetLogger()
{
    var logger = LogManager.GetCurrentClassLogger();
    var d1 = (DatabaseTarget)logger.Factory.Configuration
        .AllTargets.Where(t => t.Name == "d1").FirstOrDefault();
    d1.DBPassword = Encryption.ToInsecureString(
        Encryption.DecryptString(((NLog.Layouts.SimpleLayout)(d1.DBPassword)).Text));
    return logger;
}

直到现在使用记录器:

static void Main(string[] args)
{
    LogEventInfo myEvent = new LogEventInfo(LogLevel.Debug, "", "My debug message");
    myEvent.LoggerName = logger.Name;
    myEvent.Properties.Add("MyCustomValue", "This is from MyClass");
    logger.Log(myEvent);
}