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.FileInputStream;
047    import java.io.FileOutputStream;
048    import java.math.BigInteger;
049    import java.security.MessageDigest;
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    
058    
059    
060    /**
061     * This demo program uses a PKCS#11 module to calculate a hash of a given file.
062     * Optionally the calcualted raw hash can be written to file. The program also
063     * verifies the calculated hash with a software hash from Java.
064     *
065     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
066     * @version 0.1
067     * @invariants
068     */
069    public class Digest {
070    
071      public static void main(String[] args) {
072        if ((args.length != 3) && (args.length != 4)) {
073          printUsage();
074          System.exit(1);
075        }
076    
077        try {
078    
079            Module pkcs11Module = Module.getInstance(args[0]);
080            pkcs11Module.initialize(null);
081    
082            Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);
083    
084            if (slots.length == 0) {
085              System.out.println("No slot with present token found!");
086              System.exit(0);
087            }
088    
089            Slot selectedSlot = slots[0];
090            Token token = selectedSlot.getToken();
091    
092            Session session =
093                token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RO_SESSION, null, null);
094    
095            // login user
096            //session.login(Session.UserType.USER, args[1].toCharArray());
097    
098            System.out.println("################################################################################");
099            System.out.println("digesting data from file: " + args[2]);
100    
101    
102            //be sure that your token can process the specified mechanism
103            Mechanism digestMechanism = Mechanism.SHA_1;
104    
105            byte[] dataBuffer = new byte[4096];
106            byte[] helpBuffer;
107            int bytesRead;
108            
109            FileInputStream dataInputStream = new FileInputStream(args[2]);
110            
111            int updateCounter = 0;
112            long t0 = System.currentTimeMillis();
113    
114            // initialize for digesting
115            session.digestInit(digestMechanism);
116            // feed in all data from the input stream
117            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
118              if (bytesRead < dataBuffer.length) {
119                helpBuffer = new byte[bytesRead]; // we need a buffer that only holds what to send for digesting
120                System.arraycopy(dataBuffer, 0, helpBuffer, 0, bytesRead);
121                session.digestUpdate(helpBuffer);
122              } else {
123                session.digestUpdate(dataBuffer);
124              }
125              updateCounter++;
126            }
127            byte[] digestValue = session.digestFinal();
128            
129            long t1 = System.currentTimeMillis();
130    
131            dataInputStream.close();        
132    
133            Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory
134            
135            System.out.println("The digest value is: " + new BigInteger(1, digestValue).toString(16));
136            System.out.println("Calculation took " + (t1 - t0) + " milliseconds using " + updateCounter + " update calls.");
137    
138            if (args.length == 4) {
139              System.out.println("Writing digest value to file: " + args[3]);
140    
141              FileOutputStream signatureOutput = new FileOutputStream(args[3]);
142              signatureOutput.write(digestValue);
143              signatureOutput.flush();
144              signatureOutput.close();
145            }
146      
147            System.out.println("################################################################################");
148    
149    
150            System.out.println("################################################################################");
151            System.out.println("verifying digest with software digest");
152    
153            MessageDigest softwareDigestEngine = MessageDigest.getInstance("SHA-1");
154    
155            dataInputStream = new FileInputStream(args[2]);
156    
157            updateCounter = 0;
158            t0 = System.currentTimeMillis();
159            
160            // feed in all data from the input stream
161            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
162              softwareDigestEngine.update(dataBuffer, 0, bytesRead);
163              updateCounter++;
164            }
165            byte[] softwareDigestValue = softwareDigestEngine.digest();
166    
167            t1 = System.currentTimeMillis();
168            
169            dataInputStream.close();
170            
171            Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory
172    
173            System.out.println("The digest value is: " + new BigInteger(1, softwareDigestValue).toString(16));
174            System.out.println("Calculation took " + (t1 - t0) + " milliseconds using " + updateCounter + " update calls.");
175            
176            if (Arrays.equals(digestValue, softwareDigestValue)) {
177              System.out.println("Verified Message Digest successfully");
178            } else {
179              System.out.println("Verification of Message Digest FAILED");
180            }
181    
182            System.out.println("################################################################################");
183    
184    
185            session.closeSession();
186            pkcs11Module.finalize(null);
187    
188        } catch (Throwable thr) {
189          thr.printStackTrace();
190        }
191      }
192    
193      public static void printUsage() {
194        System.out.println("Usage: Digest <PKCS#11 module> <user-PIN> <file to be digested> [<digest value file>]");
195        System.out.println(" e.g.: Digest pk2priv.dll password data.dat digest.bin");
196        System.out.println("The given DLL must be in the search path of the system.");
197      }
198    
199    }