1 /*
2  * @(#) $Id: CreateSignature.java,v 1.3 2003/07/08 08:13:52 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10
11import java.io.FileInputStream;
12import java.io.FileOutputStream;
13import org.w3c.dom.Document;
14import java.security.PrivateKey;
15import java.security.cert.X509Certificate;
16
17import com.verisign.xmlsig.Signer;
18import com.verisign.xpath.XPath;
19
20public class CreateSignature {
21    public static void main(String[] args) throws Exception {
22        // Input to signature.
23        String datafile = "book.xml";
24        String sigfile = "sig.xml";
25        XPath tobeSigned1 = new XPath("id('book_info')");
26        XPath tobeSigned2 = new XPath("id('book_title')");
27        XPath sigloc = new XPath("id('book_title')");
28        System.out.println("Signing two elements of file \"" + datafile + "\"");
29
30        // Info to get Signing Key.
31        String keystore = "my.keystore";
32        String storepass = "changeit";
33        String kstype = "JCEKS";
34        String alias = "mykey";
35        System.out.println("Using private key in keystore \"" + keystore + "\" ...");
36
37        // Get the private key and corresponding certificate.
38        FileInputStream fis = new FileInputStream(keystore);
39        java.security.KeyStore ks = java.security.KeyStore.getInstance(kstype);
40        ks.load(fis, storepass.toCharArray());
41        PrivateKey key = (PrivateKey)ks.getKey(alias, storepass.toCharArray());
42        X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
43
44        // Read the XML file
45        Document doc = XmlUtility.readXML(datafile);
46
47        Signer signer = new Signer(doc, key, cert);
48        signer.addReference(tobeSigned1);
49        signer.addReference(tobeSigned2);
50
51        // signer.useExclusiveCanonicalizer(java.util.Collections.EMPTY_LIST);
52        Document signedDoc = signer.sign(sigloc, true);
53
54        // Write the signed XML file
55        XmlUtility.writeXML(signedDoc, new FileOutputStream(sigfile));
56
57        System.out.println();
58        System.out.println("Signature Creation SUCCESSFUL!!");
59        System.out.println("Signature written to file: " + sigfile);
60    }
61}