如何使用 dotnet 核心加密具有多个 x509 证书的文本消息 [英] How to encrypt a text message with multiple x509 certificates with dotnet core
问题描述
我想用多个 x509 证书(公钥)加密一条短信.
I would like to encrypt a text message with multiple x509 certificates (public keys).
这就是我现在所拥有的:
This is what I have right now:
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 个公钥加密文本.我无法弄清楚如何使用多个证书来做到这一点.这完全可行吗?有意义吗?
This would let me encrypt the text with 1 public key. I Can not figure out how to do it with multiple certificates. Is this doable at all and does it makes sense?
基本上是这样的……但没有 XML 和 dotnetcore 5具有X509证书的多个收件人的XML加密和解密一个>
Basically something like this... but without the XML and with dotnetcore 5 XML encryption and decryption for multiple recipients with X509 certificates
推荐答案
@Crypt32 为算法流程给出的答案是准确的.如果您同意每个人都收到每个人的加密密钥 blob,那么这恰好描述了 EnvelopedCms
(和加密电子邮件)的工作原理.
The answer that @Crypt32 gave for the algorithmic flow is spot-on. If you're OK with everyone receiving everyone's encrypted key blobs then that happens to describe precisely how EnvelopedCms
(and encrypted e-mail) works.
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);
}
这篇关于如何使用 dotnet 核心加密具有多个 x509 证书的文本消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!