使用C#解码PKCS7 SMIME数据

时间:2018-04-21 13:08:51

标签: c# openssl smime

我正在使用openssl使用以下

加密数据
openssl smime -encrypt -in data.json -aes256 certificate.pem

data.json内容:

{"array":[1,2,3],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}

结束于:

MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; 
name="smime.p7m"
Content-Transfer-Encoding: base64

MIIF6AYJKoZIhvcNAQcDoIIF2TCCBdUCAQAxggUeMIIFGgIBADCBpzCBmTELMAkG
A1UEBhMCSUwxEDAOBgNVBAgTB0NlbnRyYWwxEDAOBgNVBAcTB1JhYW5hbmExDzAN
BgNVBAoTBmFtZG9jczEMMAoGA1UECxMDV01UMSUwIwYDVQQDExxtYWNyZXBvcnRp
bmcuY29ycC5hbWRvY3MuY29tMSAwHgYJKoZIhvcNAQkBFhF3bXRhbGxAYW1kb2Nz
LmNvbQIJAPKpzLFUszFYMA0GCSqGSIb3DQEBAQUABIIEWk/ImeSYH1yGgK9wscxS
RZlqt9UurQY3wH9ZSlQEv0WyGJndmveYfEtKfOoem99TCyqopYDFfWcqGwnv57eS
fP4XHTVw4AD14zznq4gfPJjLhtXBTcjFtkgqQLsN/fOUTV2ic+nAjnAa7Okw7kd0
lXwwBtpdcD9EvMvteN1DYsLLvon6qQ3Ba1r2PYGgvmezz8WG6AAmz8h3yGtXeAqH
+e0z2aT/Ob9lpGJuvGqJUXjkcvJrVuuWPplubR5I1FJfpD+sECgw/w+swt30VLcf
Spaysm2DiiYXdyu8k/fWVhiNjNCD8D1yTJR5wvBVOFNiQs++DtagFxb8Z+Njp/hv
lBWCN+F9twPzlH16bg/6PWXLbSNMk61ixWdjWMqtaeI3hRIqRla5uQL131yIGXzy
PN4XIyMQnwMSSvsQR2IMKEN6WAdGn4+v5U2IQAjbBRPiruMf+q0BVKu97rxXGffg
2MaB3PjwofBknY+SO9m9Nfyf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NzlaXPYtkwuuAgYAZywPG
zMizOuIhL875mrW6gjzf5nKR1EsnFoRKQ6X/9/k348YHld714JpzA2vpW7UNtvir
MYnoiSPSzQ8CbYJXrAoMMB6sfMG1fJe+wUVjef2cqSZ2oiuYvTtpmXsuQGOtvWlj
XJ/pHqF8PjqjiocUKHMJJgPcds077lUmPMNmZg==

我正在寻找一种在C#中使用私钥(PEM文件)解密的方法 但是,我发现的一切都是半烘焙/没有适当的文档或示例

有什么想法吗?建议?

谢谢!

1 个答案:

答案 0 :(得分:0)

您的部分问题是S / MIME需要加密MIME实体,而不是内容数据。换句话说,如果您决定对json数据进行base64编码(例如Content-Transfer-Encoding),首先需要添加MIME标头,例如Content-Type标头和其他标题。

例如:

Content-Type: text/json

{"array":[1,2,3],"boolean":true,"null":null,"number":123,"object":{"a":"b","c":"d","e":"f"},"string":"Hello World"}

使用MimeKit完成后,您可以执行此操作来解密它:

var pkcs7 = (ApplicationPkcs7Mime) MimeEntity.Load (stream);
MimePart mime;

using (ctx = new WindowsSecureMimeContext ()) {
    mime = (MimePart) pkcs7.Decrypt (ctx);
}

using (var content = new MemoryStream ()) {
    mime.Content.DecodeTo (content);

    // now your raw json data is contained in the `content` stream.
}