首页 > 解决方案 > 如何使用 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 证书的多个收件人

标签: c#encryption.net-corex509.net-5

解决方案


@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);
}

推荐阅读