JScript Source: signature.js

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - Digital Signatures

JScript Source: signature.js

var xmldoc, xmldsig, dsigKey
var szResult = "";
KEYVALUE = 1;
DSIGNS = "xmlns:ds='http://www.w3.org/2000/09/xmldsig#'";
PROV_RSA_FULL = 1;
// Define constant for Diffie-Hillman or other cryptographic 
// provider if not using RSA full provider.
// PROV_DSS_DH   = 13;

if (loadSignature("signature_template.xml")) {
  // Change this key container name to your own if necessary.
  if (signWithKey(PROV_RSA_FULL, "MyRSAFullKeys")) {
     alert(szResult);
  }
}

/////////  Helper functions: /////////
function alert(str) { WScript.echo(str); } 

///////// Set signature for signing. ////////
function loadSignature(file)
{
   try {
     xmldoc = new ActiveXObject("Msxml2.DOMDOcument.5.0");
     xmldsig= new ActiveXObject("Msxml2.MXDigitalSignature.5.0");
   }
   catch (e) {
     alert("Installation of mxsml5 is required to run this app.\n");
     return false;
   }
   
   xmldoc.async = false;
   xmldoc.preserveWhiteSpace = true;
   xmldoc.validateOnParse = false;
   xmldoc.resolveExternals = false;
   
   if (!xmldoc.load(file)) {
     alert("Can't load "+ file + "\n");
     return false;
   }
   szResult += "\nInput signature template:\n\n" + xmldoc.xml;

   xmldoc.setProperty("SelectionNamespaces", DSIGNS);

   // Set the signature property value to the first 
   // <ds:Signature> element.
   xmldsig.signature = xmldoc.selectSingleNode(".//ds:Signature");


   return true;
}

function signWithKey(dwCspType, szKeyContainer)
{
   // Read the signature property to verify that it's been set.
   if (!xmldsig.signature) {
      alert("Must set signature template before signing.\n");
      return false;
   }
   var oKey = xmldsig.createKeyFromCSP(dwCspType, "", szKeyContainer, 0);
   var oSignedKey = xmldsig.sign(oKey, KEYVALUE); 
   if (oSignedKey == null) {
      alert("Signing failed.\n");
   }
   else {
      szResult += ("\nThe data referenced in the signature template " +
            "was signed successfully.\n" + 
            "Resultant signature:\n\n" +
             xmldoc.xml );
   }
   return true;
}

Try It!

  1. Ensure that you have completed all the procedures in Getting Started with XML Digital Signatures.
  2. Copy the XML signature template, and paste it into a text file. Save the file as signature_template.xml.
  3. Copy the JScript listing above, and paste it into a text file. Save the file as signature.js, in the same directory where you saved signature_template.xml.
  4. From a command prompt, navigate to this directory, then type "cscript signature.js".
    Note   Under operating systems other than Windows 2000 or Windows XP, you might need to install Windows Scripting Host (to run wscript.exe or cscript.exe), if it is not already installed.
  5. Verify that your output is similar to that listed in the Output topic.