【问题标题】:SQL CLR created in C# cannot access local cert store在 C# 中创建的 SQL CLR 无法访问本地证书存储
【发布时间】:2015-09-02 16:27:02
【问题描述】:

我无法创建 SQL CLR 来从证书存储区执行解密函数和加密函数,并从证书中获取结果字符串。

'System.Security.SecurityException:请求'System.Security.Permissions.StorePermission,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=blahblahblahblah'类型的权限失败。 System.Security.SecurityException:'

有没有办法让 SQL CLR 可以访问您可以更改的系统配置或其他信任设置中的证书存储?我是否需要加载依赖的 System.Security.Cryptography 依赖库?我最终也想在 Azure SQL Server 上进行设置,所以这也可能是一个障碍。我知道我的解密和加密在硬编码从模式所需的证书获得的结果数据时工作正常。但是访问证书会更好:

fDecrypt('mythumbprintstringtofinditlocally', 'DLQUOUIEWLKCJLAKJA=!@#$'(一些使用本地证书加密的数据)

而不是硬编码数据。因为此证书可能会因环境而变化。

private void SetEncryptionDirectlyFromThumbprint(string certThumbprint)
{
    var cert = GetCertificateByThumbprint(certThumbprint, StoreLocation.LocalMachine, StoreName.My);
}

//needs System.Security.Cryptography library.
private X509Certificate2 GetCertificateByThumbprint(string thumbprint, StoreLocation storeLocation, StoreName storeName, bool requirePrivateKey = false)
{
    if (string.IsNullOrEmpty(thumbprint))
    {
        throw new ArgumentNullException("thumbprint");
    }

    var cleanedThumbprint = thumbprint.Replace(" ", "").ToUpperInvariant();

    var store = new X509Store(storeName, storeLocation);

    try
    {
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);

        var foundCerts = store.Certificates.Find(X509FindType.FindByThumbprint, cleanedThumbprint, false);
        foreach (var cert in foundCerts)
        {
            if (!requirePrivateKey || cert.HasPrivateKey)
            {
                return cert;
            }
        }
    }
    finally
    {
        store.Close();
    }

    return null;
}

【问题讨论】:

    标签: c# encryption sql-server-2012 cryptography sqlclr


    【解决方案1】:

    看起来到目前为止,它只是在 Project>SQLCLR>Permission Level 下设置的“权限级别”。我将其更改为“External_Access”,瞧,它立即起作用了。现在问题似乎是 Azure 只喜欢安全程序集,并且最近才包含使用 CLR 的能力。啊,我猜是赢不了他们。

    【讨论】:

    • 在两个方面都正确:1) 访问数据库外部的任何内容都需要 WITH PERMISSION_SET = EXTERNAL_ACCESS,以及 2) SQLCLR 已在 V12 Azure SQL 数据库中引入,但仅适用于 SAFE 程序集,并且仅使用 FROM 0x01231... 而不是 FROM 'path\to\file.dll' 加载。所以不,这在 Azure SQL 数据库中不起作用:-(
    • 这很糟糕,但我认为我可以做部分工作,但仍然可能是安全的。感谢您对我的假设的确认。
    猜你喜欢
    • 2011-04-06
    • 2014-01-17
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2012-02-20
    相关资源
    最近更新 更多