如何使用公钥加密字符串并使用 MimeKit 使用私钥解密?
Posted
技术标签:
【中文标题】如何使用公钥加密字符串并使用 MimeKit 使用私钥解密?【英文标题】:How to encrypt string with public key and decrypt using private key using MimeKit? 【发布时间】:2021-04-01 18:27:35 【问题描述】:我很难寻找有关如何使用公钥证书加密字符串并使用 Mimekit 使用私钥证书对其进行解密的解决方案。这是我使用公钥证书加密文本文件的代码:
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 的新手。如果有人知道我该怎么做,那将是一个很大的帮助。
【问题讨论】:
这能回答你的问题吗? How to use public and private key encryption technique in C# 我不确定我是否理解问题所在。您说您想避免将内容写入文件,但您所做的只是将其写入文件,然后将其读回内存以便将其传递给 MimeKit。为什么不先将其写入内存,然后像现在一样将其与 MimeKit 一起使用? 【参考方案1】: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;
【讨论】:
以上是关于如何使用公钥加密字符串并使用 MimeKit 使用私钥解密?的主要内容,如果未能解决你的问题,请参考以下文章