1 /*
2  * @(#) $Id: WSSSign.java,v 1.2 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.xmlsig.SigningKey;
19import com.verisign.xmlsig.SigningKeyFactory;
20import com.verisign.xmlsig.KeyInfo;
21import com.verisign.messaging.WSSecurity;
22import com.verisign.xpath.XPath;
23
24public class WSSSign {
25    public static void main(String[] args) throws Exception {
26        // Input to signature.
27        if (args.length < 1){
28            System.out.println("Usage:: java WSSSign <inp-file> [<out-file>]");
29            return;
30        }
31        String datafile = args[0];
32        String outfile = "signed.xml";
33        if (args.length > 1)
34            outfile = args[1];
35
36        // Info to get Signing Key.
37        String keystore = "my.keystore";
38        String storepass = "changeit";
39        String kstype = "JCEKS";
40        String alias = "mykey";
41
42        System.out.println("Signing XML data in file \"" + datafile + "\"");
43        System.out.println("Using private key in keystore \"" + keystore + "\" ...");
44
45        // Get the private key and corresponding certificate.
46        FileInputStream fis = new FileInputStream(keystore);
47        java.security.KeyStore ks = java.security.KeyStore.getInstance(kstype);
48        ks.load(fis, storepass.toCharArray());
49        PrivateKey key = (PrivateKey)ks.getKey(alias, storepass.toCharArray());
50        X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
51
52        // Read the XML file
53        Document doc = XmlUtility.readXML(datafile);
54        SigningKey sk = SigningKeyFactory.makeSigningKey(key);
55        KeyInfo ki = new KeyInfo();
56        ki.setCertificate(cert);
57
58        WSSecurity wss = new WSSecurity();
59        wss.sign(doc, sk, ki);
60
61        // Write the signed XML file
62        XmlUtility.writeXML(doc, new FileOutputStream(outfile));
63        System.out.println("... Wrote the output to file: \"" + outfile + "\"");
64    }
65}