首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用MimeKit对字符串进行公钥加密和私钥解密?

如何使用MimeKit对字符串进行公钥加密和私钥解密?
EN

Stack Overflow用户
提问于 2020-12-23 12:32:05
回答 1查看 86关注 0票数 0

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

代码语言:javascript
复制
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的使用还很陌生。如果有人知道我如何做到这一点,这将是一个很大的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-24 06:43:24

代码语言:javascript
复制
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;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65419068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档