简体   繁体   English

如何创建自签名证书来签署 MimeKit 消息?

[英]How to create a self-sign certificate to sign a MimeKit Message?

How to create a self-signed certificate for development suitable to sign MimeKit Messages?如何创建适合签署 MimeKit 消息的开发自签名证书?

MimeKit has its own CmsSigner. MimeKit 有自己的 CmsSigner。 When i try to load the certificate into MimeKit CmsSigner:当我尝试将证书加载到 MimeKit CmsSigner 中时:

X509Certificate2 cert = new X509Certificate2(@"cert.pfx", "xpto", X509KeyStorageFlags.Exportable);
var signer = new MimeKit.Cryptography.CmsSigner(cert);

it throws:它抛出:

'The certificate cannot be used for signing.' “证书不能用于签名。”

The problem is that the default algorithm used by CmsSign has to be the same algorithm used to create the certificate key, in my case, SHA1. 问题在于,CmsSign使用的默认算法必须与用于创建证书密钥(在我的情况下为SHA1)的算法相同。

Here how was loaded for an S/MIME certificate: 这里是如何为S / MIME证书加载的:

X509Certificate2 cert = new X509Certificate2(@"ca.p12", "xpto", X509KeyStorageFlags.Exportable);
var signer = new CmsSigner(cert);
signer.DigestAlgorithm = DigestAlgorithm.Sha1;
MultipartSigned.Create( signer, mimeMessage.Body);
 var message = new MimeMessage() {  ... };

// Load your x509 certificate
x509certificate2 cert = new x509certificate2("d:\\mycer.pfx", "123456789", x509keystorageflags.exportable);

// CmsSigner = CMS = Cryptographic Message Syntax = a standard syntax for storing signed and/or encrypted data
var signer = new cmssigner(cert);
signer.digestalgorithm = digestalgorithm.sha256;

// This will sign the message body using our certificate which includes our organisation name
// Needs this package to run: https://www.nuget.org/packages/System.Data.SQLite/
message.body = multipartsigned.create(signer, message.body); 


// Getting the private key from the pfx file
// https://www.asptricks.net/2016/09/how-to-export-private-key-from.html
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa);
var myCAprivateKey = keyPair.Private;
                
                
// Now sign the message with the private key only to authenticate DKIM
DkimSigner Signer = new DkimSigner(
 myCAprivateKey,
 "mydomain.com", // your domain name
 "myDKIM")      // The dkim selector on  your domain's DNS (txt record)
{
    HeaderCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Relaxed,
    BodyCanonicalizationAlgorithm = DkimCanonicalizationAlgorithm.Relaxed,
    AgentOrUserIdentifier = "@mydomain.com", // your domain name
    QueryMethod = "dns/txt",
    SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha1
};
Signer.Sign(message, headers);


// do your sending logic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM