1 /*
2  * @(#) $Id: WSSEncrypt.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.ObjectInputStream;
13import java.io.FileOutputStream;
14import org.w3c.dom.Document;
15import java.security.PublicKey;
16import javax.crypto.SecretKey;
17import java.security.cert.X509Certificate;
18
19import com.verisign.xmlsig.KeyInfo;
20import com.verisign.messaging.WSSecurity;
21import com.verisign.xmlenc.AlgorithmType;
22import com.verisign.xpath.XPath;
23
24public class WSSEncrypt {
25    public static void main(String[] args) throws Exception {
26        if (args.length < 1){
27            System.out.println("Usage:: java WSSEncrypt <inp-file> [<out-file>]");
28            return;
29        }
30        String datafile = args[0];
31        String outfile = "encrypted.xml";
32        if (args.length > 1)
33            outfile = args[1];
34
35        String keystore = "my.keystore";
36        String storepass = "changeit";
37        String kstype = "JCEKS";
38        String alias = "rsakey";
39        String keyfile = "3des.key";
40
41        System.out.println("Encrypting XML data in file \"" + datafile + "\"");
42        System.out.println("Using secret key in file \"" + keyfile + "\" ...");
43        System.out.println("And encrypting the secret key");
44        System.out.println("Using public key in \"" + keystore + "\" at alias \"" + alias + "\"...");
45
46        // Get the private key and corresponding certificate.
47        FileInputStream fis = new FileInputStream(keystore);
48        java.security.KeyStore ks = java.security.KeyStore.getInstance(kstype);
49        ks.load(fis, storepass.toCharArray());
50        X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
51        PublicKey pubk = cert.getPublicKey();
52
53        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(keyfile));
54        SecretKey key = (SecretKey)ois.readObject();
55
56        // Read the XML file
57        Document doc = XmlUtility.readXML(datafile);
58        KeyInfo ki = new KeyInfo();
59        ki.setCertificate(cert);
60
61        WSSecurity wss = new WSSecurity();
62        wss.encrypt(doc, key, AlgorithmType.TRIPLEDES, pubk, AlgorithmType.RSA1_5, ki);
63
64        // Write the signed XML file
65        XmlUtility.writeXML(doc, new FileOutputStream(outfile));
66        System.out.println("... Wrote the output to file: \"" + outfile + "\"");
67    }
68}