如何使用 public 密钥加密字符串并使用 MimeKit 使用私钥解密?

How to encrypt string with public key and decrypt using private key using MimeKit?

我很难找到一个解决方案,了解如何使用 public 密钥证书加密字符串并使用 Mimekit 使用私钥证书对其进行解密。这是我使用 public 密钥证书加密文本文件的代码:

public string encryptFile(string filename)
{
    var certificate2 = new X509Certificate2(Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, /Sample.crt));
    MimeEntity body;

    using (var content = new MemoryStream(File.ReadAllBytes(filename)))
    {
        var part = new MimePart(MimeTypes.GetMimeType(filename))
        {
            ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
            ContentTransferEncoding = ContentEncoding.Binary,
            FileName = Path.GetFileName(filename),
            Content = new MimeContent(content)
        };


        var recipient = new CmsRecipient(certificate2)
        {
            EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }
        };
        var recipients = new CmsRecipientCollection();
        recipients.Add(recipient);

        using (var ctx = new TemporarySecureMimeContext())
            body = ApplicationPkcs7Mime.Encrypt(ctx, recipients, part);
    }

    string response = body.ToString();
    return response;
}

但是使用这种方式我在加密之前将我想要加密的字符串写入文件。我想做的是直接使用 MimeKit 加密字符串。我只是刚开始使用 MimeKit。如果有人知道我该怎么做,那将是一个很大的帮助。

public string EncryptString(string value)
{
    var certificate2 = new X509Certificate2(Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, /Sample.crt));
    MimeEntity body;

    using (var content = new MemoryStream(Encoding.UTF8.GetBytes (value)))
    {
        var part = new MimePart(MimeTypes.GetMimeType(filename))
        {
            ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
            ContentTransferEncoding = ContentEncoding.Binary,
            FileName = Path.GetFileName(filename),
            Content = new MimeContent(content)
        };


        var recipient = new CmsRecipient(certificate2)
        {
            EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }
        };
        var recipients = new CmsRecipientCollection();
        recipients.Add(recipient);

        using (var ctx = new TemporarySecureMimeContext())
            body = ApplicationPkcs7Mime.Encrypt(ctx, recipients, part);
    }

    using (var memory = new MemoryStream ()) {
        body.WriteTo (memory);

        string response = Encoding.UTF8.GetString (memory.ToArray ());
        return response;
    }
}