c# - 如何使用 dotnet 核心加密具有多个 x509 证书的短信
问题描述
我想用多个 x509 证书(公钥)加密一条短信。
这就是我现在所拥有的:
X509Certificate2 cert = new X509Certificate2(rawBytes);
using(RSA rsa = cert.GetRSAPublicKey()){
var txtBytes = Encoding.ASCII.GetBytes("hello world");
var encryptedBytes = rsa.Encrypt(txtBytes, RSAEncryptionPadding.OaepSHA256);
Console.Writline(Convert.ToBase64String(encryptedBytes);
}
这将让我用 1 个公钥加密文本。我不知道如何使用多个证书来做到这一点。这完全可行吗?有意义吗?
基本上是这样的......但没有 XML 和 dotnetcore 5 XML 加密和解密具有 X509 证书的多个收件人
解决方案
@Crypt32 为算法流程给出的答案是准确的。如果您对每个人都收到每个人的加密密钥 blob 都满意,那么这恰好可以准确地描述EnvelopedCms
(和加密电子邮件)的工作方式。
private static byte[] EncryptMessage(
string message,
X509Certificate2Collection recipientCerts)
{
byte[] data = Encoding.UTF8.GetBytes(message);
EnvelopedCms cms = new EnvelopedCms(new ContentInfo(data));
CmsRecipientCollection recipients = new CmsRecipientCollection();
foreach (X509Certificate2 cert in recipientCerts)
{
recipients.Add(
new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, cert));
}
cms.Encrypt(recipients);
return cms.Encode();
}
/// <param name="extraCerts">
/// An optional collection of certificates which is used, in addition to the
/// appropriate certificate stores, to try to decrypt one of the encrypted keys.
/// </param>
private static string DecryptMessage(
byte[] encodedMessage,
X509Certificate2Collection extraCerts = null)
{
EnvelopedCms cms = new EnvelopedCms();
cms.Decode(encodedMessage);
if (extraCerts == null)
{
cms.Decrypt();
}
else
{
cms.Decrypt(extraCerts);
}
return Encoding.UTF8.GetString(cms.ContentInfo.Content);
}
推荐阅读
- ajax - v-for 在 AJAX 请求后渲染
- django - 从 django 管理视图中的自定义按钮调用 API
- chart.js - 如何使chartjs-plugin-streaming中的x轴从零开始?
- flutter - 构建后使用网络颤振firebase电话身份验证问题
- php - PHP 警告:PHP 启动:无法加载动态库 '/path/to/extension/mysqli.so'
- elixir - 如何在发布请求期间在 Phoenix 插件测试中传递这些 url 编码参数,以便 Plug.Conn.read_body 读取它?
- rider - Rider Reformat 如何调整白线?
- discord.js - client.commands.get('kickembed').execute //无法读取属性'execute'未定义//
- php - 使用 PHP 和 Mysql、Laravel 自定义消息/模板内容
- laravel - 实例化模型与查找模型之间的区别