使用自定义配置提供程序解密

时间:2019-03-01 16:11:21

标签: c# json encryption .net-core

我一直在寻找用于将加密的连接信息存储在Appsettings.json中并使用ConfigProvider扩展对其解密的解决方案。我走这条路,因为我应该能够在所有生产应用程序上重用它。秘密和Azure Key保险库似乎不是我要找的东西,也没有使用的选择。

我暂时基于this

我的json文件看起来与此类似

{
  "ConnectionStrings": {
    "SerilogConnection": "encryptedConnection",
    "OracleConnection": "encryptedConnection"
  }
}

我很难弄清楚如何使用解密的密钥将json加载到此字典对象中,以及如何在配置生成器中将其返回...

private IDictionary<string, string> UnencryptMyConfiguration()
        { 
            // how do parse json this and decrypt?
            // var jObj = JObject.Parse(json);
            // var innerJObj = JObject.FromObject(jObj["ConnectionStrings"]);
            // use decryption method here?
            var configValues = new Dictionary<string, string>
            {
                {"key1", "unencryptedValue1"},
                {"key2", "unencryptedValue2"}
            };

            return configValues;
        }

建筑商为此照顾我吗?

    var configuration = new ConfigurationBuilder()
        .AddJsonFile($"appsettings.{_currentEnv}.json", optional: true)
        .AddJsonFile("appsettings.json")
        .AddEncryptedProvider() // <-- here?
        .AddEnvironmentVariables()
        .Build();

这是我在另一个项目中使用的解密方法:

public string DecryptData(string data)
{
    string path = @"c:\temp\PrivateKey.txt";
    var privateKey = System.IO.File.ReadAllText(path);

    var bytesCypherText = Convert.FromBase64String(data);

    var csp = new RSACryptoServiceProvider();
    var sr = new System.IO.StringReader(privateKey);
    var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
    var privKey = (RSAParameters)xs.Deserialize(sr);
    csp.ImportParameters(privKey);

    var bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

    var plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
    return plainTextData;
}

我看了很多资源,读了this一堆,但似乎并不是我真正想要的东西。任何指示或建议都欢迎,我走错了路吗?

0 个答案:

没有答案
相关问题