1 /*
2  * @(#) $Id: Encrypt1.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.ObjectInputStream;
13import java.io.FileOutputStream;
14import org.w3c.dom.Document;
15import java.security.KeyPair;
16import java.security.PublicKey;
17import javax.crypto.SecretKey;
18
19import com.verisign.xmlenc.Encryptor;
20import com.verisign.xmlenc.AlgorithmType;
21import com.verisign.xpath.XPath;
22
23public class Encrypt1 {
24    public static void main(String[] args) throws Exception {
25        // Input to encryption.
26        String datafile = "book.xml";
27        String encfile = "enc.xml";
28        XPath encloc = new XPath("id('book_info')");
29        System.out.println("Encrypting element with id=book_info of file \"" + datafile + "\"");
30
31        // Info to get Secret Key and Key Pair.
32        String kpfile = "rsa.kp";
33        String keyfile = "3des.key";
34        System.out.println("Using RSA key-pair in file \"" + kpfile + "\" ...");
35
36        // Get the secret key and key pair from file.
37        FileInputStream fis = new FileInputStream(kpfile);
38        ObjectInputStream ois = new ObjectInputStream(fis);
39        KeyPair kp = (KeyPair)ois.readObject();
40        PublicKey pk = kp.getPublic();
41        fis = new FileInputStream(keyfile);
42        ois = new ObjectInputStream(fis);
43        SecretKey key = (SecretKey)ois.readObject();
44
45        // Read the XML file
46        Document doc = XmlUtility.readXML(datafile);
47
48        Encryptor encryptor = new Encryptor(doc,
49            key, AlgorithmType.TRIPLEDES, pk, AlgorithmType.RSA1_5);
50        Document encryptedDoc = encryptor.encrypt(encloc);
51
52        // Write the signed XML file
53        XmlUtility.writeXML(encryptedDoc, new FileOutputStream(encfile));
54
55        System.out.println();
56        System.out.println("Encryption SUCCESSFUL!!");
57        System.out.println("Document with encrypted element written to file: " + encfile);
58    }
59}