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.math.BigInteger;
051    import java.util.Arrays;
052    
053    import iaik.pkcs.pkcs11.Mechanism;
054    import iaik.pkcs.pkcs11.Module;
055    import iaik.pkcs.pkcs11.Session;
056    import iaik.pkcs.pkcs11.Slot;
057    import iaik.pkcs.pkcs11.Token;
058    import iaik.pkcs.pkcs11.TokenException;
059    import iaik.pkcs.pkcs11.objects.DES3SecretKey;
060    // import iaik.security.provider.IAIK;
061    
062    
063    
064    /**
065     * This demo program uses a PKCS#11 module to MAC a given file and test
066     * if the MAC can be verified.
067     *
068     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
069     * @version 0.1
070     * @invariants
071     */
072    public class MAC {
073    
074      static PrintWriter output_;
075    
076      static {
077        try {
078          //output_ = new PrintWriter(new FileWriter("Encrypt_output.txt"), true);
079          output_ = new PrintWriter(System.out, true);
080        } catch (Throwable thr) {
081          thr.printStackTrace();
082          output_ = new PrintWriter(System.out, true);
083        }
084      }
085    
086      public static void main(String[] args) {
087        if (args.length != 3) {
088          printUsage();
089          System.exit(1);
090        }
091    
092        try {
093            // Security.addProvider(new IAIK());
094    
095            Module pkcs11Module = Module.getInstance(args[0]);
096            pkcs11Module.initialize(null);
097    
098            Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);
099    
100            if (slots.length == 0) {
101              output_.println("No slot with present token found!");
102              System.exit(0);
103            }
104    
105            Slot selectedSlot = slots[0];
106            Token token = selectedSlot.getToken();
107    
108            Session session =
109                token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RO_SESSION, null, null);
110    
111            // login user
112            //session.login(Session.UserType.USER, args[1].toCharArray());
113    
114            output_.println("################################################################################");
115            output_.println("generate secret MAC key");
116    
117            Mechanism keyMechanism = Mechanism.DES3_KEY_GEN;
118            DES3SecretKey secretMACKeyTemplate = new DES3SecretKey();
119            secretMACKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
120            secretMACKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
121    
122            DES3SecretKey secretMACKey = (DES3SecretKey) session.generateKey(keyMechanism, secretMACKeyTemplate);
123    
124    /*
125            GenericSecretKey secretMACKeyTemplate = new GenericSecretKey();
126            secretMACKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
127            secretMACKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
128            secretMACKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
129    
130            // generate some bytes random data that we can use as test key
131            byte[] randomData = session.generateRandom(16);
132    
133            secretMACKeyTemplate.getValue().setByteArrayValue(randomData);
134            secretMACKeyTemplate.getValueLen().setLongValue(new Long(randomData.length));
135    
136            GenericSecretKey secretMACKey = (GenericSecretKey) session.createObject(secretMACKeyTemplate);
137    */
138    
139            output_.println("################################################################################");
140    
141            output_.println("################################################################################");
142            output_.println("MACing data from file: " + args[2]);
143    
144            InputStream dataInputStream = new FileInputStream(args[2]);
145    
146            //be sure that your token can process the specified mechanism
147            Mechanism signatureMechanism = Mechanism.SHA_1_HMAC;
148            // initialize for signing
149            session.signInit(signatureMechanism, secretMACKey);
150    
151            byte[] dataBuffer = new byte[1024];
152            int bytesRead;
153            ByteArrayOutputStream streamBuffer = new ByteArrayOutputStream();
154    
155            // feed in all data from the input stream
156            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
157              streamBuffer.write(dataBuffer, 0, bytesRead);
158            }
159            Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory
160            streamBuffer.flush();
161            streamBuffer.close();
162            dataInputStream.close();
163            byte[] rawData = streamBuffer.toByteArray();
164    
165            byte[] macValue = session.sign(rawData);
166    
167            output_.println("The MAC value is: " + new BigInteger(1, macValue).toString(16));
168    
169            output_.println("################################################################################");
170    
171            output_.println("################################################################################");
172            output_.print("verification of the MAC... ");
173    
174            dataInputStream = new FileInputStream(args[2]);
175    
176            // initialize for verification
177            session.verifyInit(signatureMechanism, secretMACKey);
178    
179            streamBuffer = new ByteArrayOutputStream();
180    
181            // feed in all data from the input stream
182            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
183              streamBuffer.write(dataBuffer, 0, bytesRead);
184            }
185            Arrays.fill(dataBuffer, (byte) 0); // ensure that no data is left in the memory
186            streamBuffer.flush();
187            streamBuffer.close();
188            dataInputStream.close();
189            rawData = streamBuffer.toByteArray();
190    
191            try {
192              session.verify(rawData, macValue); // throws an exception upon unsuccessful verification
193              output_.println("successful");
194            } catch (TokenException ex) {
195              output_.println("FAILED: " + ex.getMessage());
196            }
197    
198            output_.println("################################################################################");
199    
200            session.closeSession();
201            pkcs11Module.finalize(null);
202    
203        } catch (Throwable thr) {
204          thr.printStackTrace();
205        }
206      }
207    
208      public static void printUsage() {
209        output_.println("Usage: MAC <PKCS#11 module> <user-PIN> <file to be MACed>");
210        output_.println(" e.g.: MAC pk2priv.dll password data.dat");
211        output_.println("The given DLL must be in the search path of the system.");
212      }
213    
214    }