Send encrypted and signed email using C# -
i want send encrypted , signed mail without using third-party api. if send alternate view signature, windows mail can validate it. if send alternate view encrypted data, windows mail can decipher it. if send both, windows mail gets 2 attachements. if sign encryptedbytes
, add signed bytes alternative view validates signature , message empty. idea?
mailmessage message = new mailmessage(); message.from = new mailaddress(lblmail.text); message.subject = txtsubject.text; string body = "content-type: text/plain\r\ncontent-transfer-encoding: 7bit\r\n\r\n" + structform(); byte[] messagedata = encoding.ascii.getbytes(body); contentinfo content = new contentinfo(messagedata); envelopedcms envelopedcms = new envelopedcms(content); message.to.add(new mailaddress(provmail)); cmsrecipient recipient = new cmsrecipient(subjectidentifiertype.subjectkeyidentifier, this.certificate); envelopedcms.encrypt(recipient); byte[] encryptedbytes = envelopedcms.encode(); signedcms cms = new signedcms(new contentinfo(encryptedbytes)); cmssigner signer = new cmssigner(subjectidentifiertype.issuerandserialnumber, new x509certificate2(@"c:\serv.pfx","123")); cms.computesignature(signer); byte[] signedbytes = cms.encode(); memorystream encryptedstream = new memorystream(encryptedbytes); alternateview encryptedview = new alternateview(encryptedstream, "application/pkcs7-mime; smime-type=signed--data;name=smime.p7m"); message.alternateviews.add(encryptedview); memorystream signedstream = new memorystream(signedbytes); alternateview signedview = new alternateview(signedstream, "application/pkcs7-mime; smime-type=signed-data;name=sig.p7m"); message.alternateviews.add(signedview); system.net.networkcredential smtpuserinfo = new system.net.networkcredential("emailaddress@xpto.com", "xxxxxx"); smtpclient client = new smtpclient("smtp.xpto.com"); client.usedefaultcredentials = false; client.credentials = smtpuserinfo; client.send(message); label2.text = "assinado e cifrado!";
you should sign first, encrypt.
while original cms , s/mime specifications allow operations in either order, later work pointed out signing document can't read bad idea. signature should on plain-text.
the resulting mime message should have single part, should s/mime enveloped-data. message has 2 parts, , encrypted part mis-labeled signed-data content-type. create , sign signedcms
object. encode it, , use encoded value content of envelopedcms
object. encrypt that, , use encoded value content of mailmessage
, content type of "application/pkcs7-mime; smime-type=enveloped-data".
Comments
Post a Comment