asp.net-mvc-3 - 是否可以保护 CloudConfigurationManager 引用的 Azure 连接字符串?

标签 asp.net-mvc-3 azure azure-sql-database

我已阅读MSDN blog有关通过加密内容并在 Azure 上设置证书来保护 web.config 中的敏感数据以便读回这些数据的帖子。

但是,Visual Studio Azure 部署项目中的“服务配置”.cscfg 文件中有绝密数据。我们在这里存储连接字符串和其他敏感数据,以便同样位于 Azure 上的测试系统可以定向到等效的测试后端服务。

此数据是通过 CloudConfigurationManager(例如 .GetSetting("AwsSecretKey"))而不是博客文章中讨论的 WebConfigurationManager 访问的。

是否可以以类似的方式保护这些数据?重要的是,我们在测试和生产中拥有不同的 AWS 和 SQL 连接字符串,并且生产 key 对我和其他开发人员隐藏。

最佳答案

是的,我们使用部署配置中上传的 x509 证书来执行此操作。但是,这些设置的安全程度取决于您保护私钥的策略/程序!以下是我们在 Azure 角色中用于解密 ServiceConfiguration 中的值的代码:

/// <summary>Wrapper that will wrap all of our config based settings.</summary>
public static class GetSettings
{
    private static object _locker = new object();

    /// <summary>locked dictionary that caches our settings as we look them up.  Read access is ok but write access should be limited to only within a lock</summary>
    private static Dictionary<string, string> _settingValues = new Dictionary<string, string>();

    /// <summary>look up a given setting, first from the locally cached values, then from the environment settings, then from app settings.  This handles caching those values in a static dictionary.</summary>
    /// <param name="settingsKey"></param>
    /// <returns></returns>
    public static string Lookup(string settingsKey, bool decrypt = false)
    {
        // have we loaded the setting value?
        if (!_settingValues.ContainsKey(settingsKey))
        {
            // lock our locker, no one else can get a lock on this now
            lock (_locker)
            {
                // now that we're alone, check again to see if someone else loaded the setting after we initially checked it
                //  if no one has loaded it yet, still, we know we're the only one thats goin to load it because we have a lock
                //  and they will check again before they load the value
                if (!_settingValues.ContainsKey(settingsKey))
                {
                    var lookedUpValue = "";
                    // lookedUpValue = RoleEnvironment.IsAvailable ? RoleEnvironment.GetConfigurationSettingValue(settingsKey) : ConfigurationManager.AppSettings[settingsKey];
                    // CloudConfigurationManager.GetSetting added in 1.7 - if in Role, get from ServiceConfig else get from web config.
                    lookedUpValue = CloudConfigurationManager.GetSetting(settingsKey);
                    if (decrypt)
                        lookedUpValue = Decrypt(lookedUpValue);
                    _settingValues[settingsKey] = lookedUpValue;
                }
            }

        }

        return _settingValues[settingsKey];
    }

    private static string Decrypt(string setting)
    {
        var thumb = Lookup("DTSettings.CertificateThumbprint");
        X509Store store = null;

        try
        {
            store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            var cert = store.Certificates.Cast<X509Certificate2>().Single(xc => xc.Thumbprint == thumb);

            var rsaProvider = (RSACryptoServiceProvider)cert.PrivateKey;
            return Encoding.ASCII.GetString(rsaProvider.Decrypt(Convert.FromBase64String(setting), false));
        }
        finally
        {
            if (store != null)
                store.Close();
        }
    }
}

然后,您可以利用 RoleEnvironment.IsAvailable 仅解密模拟器或部署环境中的值,从而使用带有 key="MyConnectionString"的未加密应用程序设置在本地 IIS 中运行 Web 角色以进行本地调试(没有模拟器):

ContextConnectionString = GetSettings.Lookup("MyConnectionString", decrypt: RoleEnvironment.IsAvailable);

然后,为了完成示例,我们使用以下代码创建了一个简单的 WinForsm 应用程序,以使用给定的证书加密/解密该值。我们的生产团队维护对生产证书的访问,并使用 WinForms 应用程序加密必要的值。然后他们向开发团队提供加密值。您可以找到full working copy of the solution here 。以下是 WinForms 应用程序的主要代码:

    private void btnEncrypt_Click(object sender, EventArgs e)
    {
        var thumb = tbThumbprint.Text.Trim();
        var valueToEncrypt = Encoding.ASCII.GetBytes(tbValue.Text.Trim());

        var store = new X509Store(StoreName.My, rbLocalmachine.Checked ? StoreLocation.LocalMachine : StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        var cert = store.Certificates.Cast<X509Certificate2>().Single(xc => xc.Thumbprint == thumb);

        var rsaProvider = (RSACryptoServiceProvider)cert.PublicKey.Key;
        var cypher = rsaProvider.Encrypt(valueToEncrypt, false);
        tbEncryptedValue.Text = Convert.ToBase64String(cypher);
        store.Close();
        btnCopy.Enabled = true;
    }

    private void btnDecrypt_Click(object sender, EventArgs e)
    {
        var thumb = tbThumbprint.Text.Trim();
        var valueToDecrypt = tbEncryptedValue.Text.Trim();

        var store = new X509Store(StoreName.My, rbLocalmachine.Checked ? StoreLocation.LocalMachine : StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        var cert = store.Certificates.Cast<X509Certificate2>().Single(xc => xc.Thumbprint == thumb);

        var rsaProvider = (RSACryptoServiceProvider)cert.PrivateKey;
        tbDecryptedValue.Text = Encoding.ASCII.GetString(rsaProvider.Decrypt(Convert.FromBase64String(valueToDecrypt), false));
    }

    private void btnCopy_Click(object sender, EventArgs e)
    {
        Clipboard.SetText(tbEncryptedValue.Text);
    }

关于asp.net-mvc-3 - 是否可以保护 CloudConfigurationManager 引用的 Azure 连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15202726/

相关文章:

c# - 将 C# 控制台应用程序发布为 Azure Web 作业

performance - Azure Web 角色与 SQL Azure 和应用程序性能之间的延迟

asp.net - 配置 Azure Web 和 SQL 英国文化

asp.net - ASP.NET MVC 路由的无限 URL 参数

c# - 有没有一种方法可以在任一字段发生更改时触发远程验证属性?

c# - WebAPI 与 Ninject

vb.net - Asp.net MVC3 合适的模型通过VB.net

azure - 尝试更改 Azure 应用服务计划时找不到应用服务计划

Azure 验证 ID 在发布时卡住 - 日志在哪里?

azure - 无法在 Azure SQL 数据库上创建外部表