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

ASP.NET 5中使用Bouncy Castle替代X509Certificate2实现S/Mime邮件加密

适配方案

首先安装所需NuGet依赖:

  • MimeKit(已引入可跳过)
  • MailKit(已引入可跳过)
  • MimeKit.BouncyCastle(MimeKit官方BouncyCastle适配组件)
  • Portable.BouncyCastle(跨平台纯托管BouncyCastle加密实现)

修改后完整代码

using MimeKit;
using MimeKit.Cryptography;
using MailKit.Net.Smtp;
using Org.BouncyCastle.Pkcs;
using System.IO;

var message = new MimeMessage();
message.To.Add(new MailboxAddress("John Doe", "jdoe@somewhere.com"));
message.From.Add(new MailboxAddress("Jane Doe", "jndoe@somewhere.com"));
message.Headers.Add("AS3-From", "PILM");
message.Headers.Add("AS3-To", "SARS");
message.Date = DateTimeOffset.Now;
message.MessageId = "42";
message.Subject = "This is a subject";
message.Body = new TextPart("html") { Text = "This is a body" };

// 替换为BouncyCastle实现的加密上下文,完全绕过系统加密API
using (var context = new BouncyCastleSecureMimeContext())
{
    // 用BouncyCastle加载PKCS12证书,不依赖系统X509证书模块
    using var certStream = File.OpenRead(@"c:\security\smime.p12");
    var pkcs12Store = new Pkcs12Store(certStream, "VeryCoolPassword".ToCharArray());
    
    // 取出证书别名和对应私钥、证书链
    var certAlias = pkcs12Store.Aliases.Cast<string>().First(alias => pkcs12Store.IsKeyEntry(alias));
    var keyEntry = pkcs12Store.GetKey(certAlias);
    var certificate = pkcs12Store.GetCertificate(certAlias).Certificate;
    
    // 导入证书和私钥到加密上下文
    context.Import(certificate, keyEntry.Key);

    // 配置收件人加密算法为TripleDes适配低版本系统
    var recip = new CmsRecipient(certificate)
    {
        EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }
    };
    var recips = new CmsRecipientCollection { recip };

    message.Body = ApplicationPkcs7Mime.Encrypt(context, recips, message.Body);
}

// SMTP发送逻辑保持不变
using var client = new SmtpClient();
client.Connect("MySuperEmailServer", 465, true);
client.Authenticate("MySuperUserName", "VeryCoolPassword");
client.Send(message);
client.Disconnect(true);

变更说明

  • 加密上下文从TemporarySecureMimeContext替换为BouncyCastleSecureMimeContext后,所有S/MIME加密逻辑完全使用BouncyCastle纯托管实现,不依赖Windows系统加密API,同时兼容Windows Server 2012和Linux容器运行环境。
  • 原有The specified network password is not correct报错是Windows Server 2012系统CAPI不支持EphemeralKeySet标识加载PKCS12证书导致,改用BouncyCastle加载证书完全绕过了该系统限制,证书密码正确的前提下不会再抛出该异常。

内容的提问来源于stack exchange,提问作者Zachary Scott

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:06:05