Sample code for 30+ languages & platforms
JavaScript

Add an S/MIME Detached Signature

See more MIME Examples

Demonstrates the Chilkat Mime.AddDetachedSignature method, which creates an S/MIME detached signature. The only argument is the signing Cert, which must have access to its private key. On success the entity becomes a multipart/signed with the content and a separate signature part.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: A detached signature (multipart/signed) keeps the original content readable alongside a separate signature part — so recipients whose software does not understand S/MIME still see the message, they just cannot verify it. That backward compatibility makes detached the usual choice for signed email. The signer proves authorship with a certificate that carries its private key.
Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat v11.4.0 or greater.
JavaScript
var success = false;

var mime = new CkMime();
success = mime.SetBodyFromPlainText("This message will be signed.");
if (success == false) {
    console.log(mime.LastErrorText);
    return;
}

//  Load the signing certificate (which must have access to its private key) from a PFX file.
//  The PFX password should come from a secure source rather than being hard-coded.
var pfxPassword = "myPfxPassword";
var cert = new CkCert();
success = cert.LoadPfxFile("qa_data/signer.pfx",pfxPassword);
if (success == false) {
    console.log(cert.LastErrorText);
    return;
}

//  Create an S/MIME detached signature.  The object becomes a multipart/signed entity with the
//  original content and a separate signature part.
success = mime.AddDetachedSignature(cert);
if (success == false) {
    console.log(mime.LastErrorText);
    return;
}

success = mime.SaveMime("qa_output/signed.eml");
if (success == false) {
    console.log(mime.LastErrorText);
    return;
}

console.log("Detached signature added.");