You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Docker/Linux部署中SQL Server Always Encrypted证书问题

问题原因

错误的核心是Windows证书存储(MSSQL_CERTIFICATE_STORE)仅支持Windows平台,Linux/Docker环境下没有这个密钥存储提供程序,导致无法解密列加密密钥(CEK)。

解决步骤

1. 调整代码配置,改用Linux兼容的密钥存储方式

放弃依赖Windows证书存储,改为直接从.pfx文件加载证书,以下是ASP.NET Core中配置DbContext的示例:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var connectionString = "你的数据库连接字符串";
    // 加载本地pfx证书
    var certificate = new X509Certificate2(
        Path.Combine(AppContext.BaseDirectory, "your-cert.pfx"),
        "证书导出密码", // 导出pfx时设置的密码
        X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

    // 配置Always Encrypted使用自定义证书提供程序
    var sqlConnection = new SqlConnection(connectionString);
    sqlConnection.ColumnEncryptionSettings = new SqlConnectionColumnEncryptionSettings(
        new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>
        {
            ["CUSTOM_CERT_PROVIDER"] = new SqlColumnEncryptionCertificateStoreProvider(certificate)
        });

    optionsBuilder.UseSqlServer(sqlConnection);
}

2. Docker/Linux环境中正确处理.pfx证书

方式一:将pfx文件嵌入Docker镜像

在Dockerfile中添加复制命令,确保证书文件被打包到镜像内:

# 假设证书文件在项目根目录的Certificates文件夹下
COPY ./Certificates/your-cert.pfx /app/Certificates/your-cert.pfx
# 设置证书文件权限,避免应用无法读取
RUN chmod 600 /app/Certificates/your-cert.pfx

方式二:(可选)将pfx导入Linux系统证书存储

如果需要将证书导入系统级存储,可执行以下命令拆分并导入:

# 从pfx中提取证书和私钥
openssl pkcs12 -in your-cert.pfx -out your-cert.crt -nokeys -clcerts
openssl pkcs12 -in your-cert.pfx -out your-cert.key -nocerts -nodes

# 将证书导入系统信任存储
sudo cp your-cert.crt /usr/local/share/ca-certificates/
sudo update-ca-certificates

注意:即使导入系统存储,仍需通过代码加载证书,Linux环境不支持MSSQL_CERTIFICATE_STORE提供程序。

3. 验证连接字符串

确保连接字符串仅保留ColumnEncryptionSetting=Enabled配置,不要包含Windows证书存储相关的额外参数。

内容的提问来源于stack exchange,提问作者Ali.Rashidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:15:53