简体   繁体   中英

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 has its own CmsSigner. When i try to load the certificate into 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.

Here how was loaded for an S/MIME certificate:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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