001    /* Copyright  (c) 2002 Graz University of Technology. All rights reserved.
002     *
003     * Redistribution and use in  source and binary forms, with or without 
004     * modification, are permitted  provided that the following conditions are met:
005     *
006     * 1. Redistributions of  source code must retain the above copyright notice,
007     *    this list of conditions and the following disclaimer.
008     *
009     * 2. Redistributions in  binary form must reproduce the above copyright notice,
010     *    this list of conditions and the following disclaimer in the documentation
011     *    and/or other materials provided with the distribution.
012     *  
013     * 3. The end-user documentation included with the redistribution, if any, must
014     *    include the following acknowledgment:
015     * 
016     *    "This product includes software developed by IAIK of Graz University of
017     *     Technology."
018     * 
019     *    Alternately, this acknowledgment may appear in the software itself, if 
020     *    and wherever such third-party acknowledgments normally appear.
021     *  
022     * 4. The names "Graz University of Technology" and "IAIK of Graz University of
023     *    Technology" must not be used to endorse or promote products derived from 
024     *    this software without prior written permission.
025     *  
026     * 5. Products derived from this software may not be called 
027     *    "IAIK PKCS Wrapper", nor may "IAIK" appear in their name, without prior 
028     *    written permission of Graz University of Technology.
029     *  
030     *  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
031     *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
032     *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
033     *  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE LICENSOR BE
034     *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
035     *  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
036     *  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
037     *  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
038     *  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
039     *  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
040     *  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
041     *  POSSIBILITY  OF SUCH DAMAGE.
042     */
043    
044    package demo.pkcs.pkcs11;
045    
046    import java.io.ByteArrayOutputStream;
047    import java.io.FileInputStream;
048    import java.io.InputStream;
049    import java.io.PrintWriter;
050    import java.util.Arrays;
051    
052    import iaik.pkcs.pkcs11.Mechanism;
053    import iaik.pkcs.pkcs11.Module;
054    import iaik.pkcs.pkcs11.Session;
055    import iaik.pkcs.pkcs11.Slot;
056    import iaik.pkcs.pkcs11.Token;
057    import iaik.pkcs.pkcs11.objects.DES3SecretKey;
058    import iaik.pkcs.pkcs11.parameters.InitializationVectorParameters;
059    // import iaik.security.provider.IAIK;
060    
061    
062    
063    /**
064     * This demo program uses a PKCS#11 module to encrypt a given file and test
065     * if the data can be decrpted.
066     *
067     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
068     * @version 0.1
069     * @invariants
070     */
071    public class EncryptDecrypt {
072    
073      static PrintWriter output_;
074    
075      static {
076        try {
077          //output_ = new PrintWriter(new FileWriter("Encrypt_output.txt"), true);
078          output_ = new PrintWriter(System.out, true);
079        } catch (Throwable thr) {
080          thr.printStackTrace();
081          output_ = new PrintWriter(System.out, true);
082        }
083      }
084    
085      public static void main(String[] args) {
086        if (args.length != 3) {
087          printUsage();
088          System.exit(1);
089        }
090    
091        try {
092            // Security.addProvider(new IAIK());
093    
094            Module pkcs11Module = Module.getInstance(args[0]);
095            pkcs11Module.initialize(null);
096    
097            Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);
098    
099            if (slots.length == 0) {
100              output_.println("No slot with present token found!");
101              System.exit(0);
102            }
103    
104            Slot selectedSlot = slots[0];
105            Token token = selectedSlot.getToken();
106    
107            Session session =
108                token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RO_SESSION, null, null);
109    
110            // login user
111            session.login(Session.UserType.USER, args[1].toCharArray());
112    
113            output_.println("################################################################################");
114            output_.println("generate secret encryption/decryption key");
115            Mechanism keyMechanism = Mechanism.DES3_KEY_GEN;
116            DES3SecretKey secretEncryptionKeyTemplate = new DES3SecretKey();
117            secretEncryptionKeyTemplate.getEncrypt().setBooleanValue(Boolean.TRUE);
118            secretEncryptionKeyTemplate.getDecrypt().setBooleanValue(Boolean.TRUE);
119    
120            DES3SecretKey encryptionKey = (DES3SecretKey) session.generateKey(keyMechanism, secretEncryptionKeyTemplate);
121    
122            output_.println("################################################################################");
123    
124            output_.println("################################################################################");
125            output_.println("encrypting data from file: " + args[2]);
126    
127            InputStream dataInputStream = new FileInputStream(args[2]);
128    
129            byte[] dataBuffer = new byte[1024];
130            int bytesRead;
131            ByteArrayOutputStream streamBuffer = new ByteArrayOutputStream();
132    
133            // feed in all data from the input stream
134            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
135              streamBuffer.write(dataBuffer, 0, bytesRead);
136            }
137            Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory
138            streamBuffer.flush();
139            streamBuffer.close();
140            byte[] rawData = streamBuffer.toByteArray();
141    
142            //be sure that your token can process the specified mechanism
143            Mechanism encryptionMechanism = Mechanism.DES3_CBC_PAD;
144            byte[] encryptInitializationVector = { 0, 0, 0, 0, 0, 0, 0, 0};
145            InitializationVectorParameters encryptInitializationVectorParameters =
146                new InitializationVectorParameters(encryptInitializationVector);
147            encryptionMechanism.setParameters(encryptInitializationVectorParameters);
148    
149            // initialize for encryption
150            session.encryptInit(encryptionMechanism, encryptionKey);
151    
152            byte[] encryptedData = session.encrypt(rawData);
153    
154            output_.println("################################################################################");
155    
156            output_.println("################################################################################");
157            output_.println("trying to decrypt");
158    
159            //Cipher des3Cipher = Cipher.getInstance("DES3/CBC/PKCS5Padding");
160    
161            Mechanism decryptionMechanism = Mechanism.DES3_CBC_PAD;
162            byte[] decryptInitializationVector = { 0, 0, 0, 0, 0, 0, 0, 0};
163            InitializationVectorParameters decryptInitializationVectorParameters =
164                new InitializationVectorParameters(decryptInitializationVector);
165            decryptionMechanism.setParameters(decryptInitializationVectorParameters);
166    
167            // initialize for decryption
168            session.decryptInit(decryptionMechanism, encryptionKey);
169    
170            byte[] decryptedData = session.decrypt(encryptedData);
171    
172            // compare initial data and decrypted data
173            boolean equal = false;
174            if (rawData.length != decryptedData.length) {
175              equal = false;
176            } else {
177              equal = true;
178              for (int i=0; i < rawData.length; i++) {
179                if (rawData[i] != decryptedData[i]) {
180                  equal = false;
181                  break;
182                }
183              }
184            }
185    
186            output_.println((equal) ? "successful" : "ERROR");
187    
188            output_.println("################################################################################");
189    
190            session.closeSession();
191            pkcs11Module.finalize(null);
192    
193        } catch (Throwable thr) {
194          thr.printStackTrace();
195        }
196      }
197    
198      public static void printUsage() {
199        output_.println("Usage: EncryptDecrypt <PKCS#11 module> <user-PIN> <file to be encrypted>");
200        output_.println(" e.g.: EncryptDecrypt pk2priv.dll password data.dat");
201        output_.println("The given DLL must be in the search path of the system.");
202      }
203    
204    }