首页 > 解决方案 > 使用自定义配置提供程序解密

问题描述

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

我现在就以此为基础

我的 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;
}

我查看了大量资源,阅读很多,但似乎没有什么是我真正想要的。欢迎任何指示或建议,我是否走错了路?

标签: c#jsonencryption.net-core

解决方案


推荐阅读