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.FileOutputStream;
049    import java.io.InputStream;
050    import java.io.OutputStream;
051    import java.io.PrintWriter;
052    import java.math.BigInteger;
053    
054    import iaik.pkcs.pkcs11.Mechanism;
055    import iaik.pkcs.pkcs11.Module;
056    import iaik.pkcs.pkcs11.Session;
057    import iaik.pkcs.pkcs11.Slot;
058    import iaik.pkcs.pkcs11.Token;
059    import iaik.pkcs.pkcs11.objects.Object;
060    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
061    
062    
063    
064    /**
065     * Signs some raw data on the token. This means, the given data is directly
066     * input to the signature cretion mechanism without any prior hashing. For
067     * instance, the user can provide the encoding of an already calcualted
068     * DigestInfo object. See file data.dat.sh1, which is the DigestInfo encoding
069     * of the SHA-1 hash of data.dat.
070     *
071     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
072     * @version 0.1
073     * @invariants
074     */
075    public class SignRaw {
076    
077      static PrintWriter output_;
078    
079      static {
080        try {
081          //output_ = new PrintWriter(new FileWriter("SignRaw_output.txt"), true);
082          output_ = new PrintWriter(System.out, true);
083        } catch (Throwable thr) {
084          thr.printStackTrace();
085          output_ = new PrintWriter(System.out, true);
086        }
087      }
088    
089      public static void main(String[] args) {
090        if ((args.length != 3) && (args.length != 4)) {
091          printUsage();
092          System.exit(1);
093        }
094    
095        try {
096    
097            Module pkcs11Module = Module.getInstance(args[0]);
098            pkcs11Module.initialize(null);
099    
100            Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);
101    
102            if (slots.length == 0) {
103              output_.println("No slot with present token found!");
104              System.exit(0);
105            }
106    
107            Slot selectedSlot = slots[0];
108            Token token = selectedSlot.getToken();
109    
110            Session session =
111                token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RO_SESSION, null, null);
112            session.login(Session.UserType.USER, args[1].toCharArray());
113    
114            output_.println("################################################################################");
115            output_.println("find private signature key");
116            RSAPrivateKey templateSignatureKey = new RSAPrivateKey();
117            templateSignatureKey.getSign().setBooleanValue(Boolean.TRUE);
118    
119            session.findObjectsInit(templateSignatureKey);
120    
121            Object[] foundSignatureKeyObjects = session.findObjects(1); // find first
122    
123            RSAPrivateKey signatureKey = null;
124            if (foundSignatureKeyObjects.length > 0) {
125              signatureKey = (RSAPrivateKey) foundSignatureKeyObjects[0];
126              output_.println("________________________________________________________________________________");
127              output_.println(signatureKey);
128              output_.println("________________________________________________________________________________");
129           } else {
130              output_.println("No RSA private key found that can sign!");
131              System.exit(0);
132            }
133            session.findObjectsFinal();
134    
135            output_.println("################################################################################");
136    
137    
138            output_.println("################################################################################");
139            output_.println("signing data from file: " + args[2]);
140    
141            InputStream dataInputStream = new FileInputStream(args[2]);
142    
143            // to buffer the data to be signed
144            ByteArrayOutputStream dataToBeSignedBuffer = new ByteArrayOutputStream(128);
145    
146            //be sure that your token can process the specified mechanism
147            Mechanism signatureMechanism = Mechanism.RSA_PKCS;
148            // initialize for signing
149            session.signInit(signatureMechanism, signatureKey);
150    
151            byte[] dataBuffer = new byte[1024];
152            byte[] helpBuffer;
153            int bytesRead;
154    
155            /* We use the sign(byte]) function, because some drivers do not support
156             * signing multiple data pieces. To buffer the data,
157             * feed all data from the input stream to the data buffer strem.
158             */
159            while ((bytesRead = dataInputStream.read(dataBuffer)) >= 0) {
160              dataToBeSignedBuffer.write(dataBuffer, 0, bytesRead);
161            }
162            byte[] dataToBeSigned = dataToBeSignedBuffer.toByteArray();
163    
164            // This signing operation is implemented in most of the drivers
165            byte[] signatureValue = session.sign(dataToBeSigned);
166    
167            output_.println("The siganture value is: " + new BigInteger(1, signatureValue).toString(16));
168    
169            if (args.length == 4) {
170              output_.println("Writing signature to file: " + args[3]);
171    
172              OutputStream signatureOutput = new FileOutputStream(args[3]);
173              signatureOutput.write(signatureValue);
174              signatureOutput.flush();
175              signatureOutput.close();
176            }
177    
178            output_.println("################################################################################");
179    
180            session.closeSession();
181            pkcs11Module.finalize(null);
182    
183        } catch (Throwable thr) {
184          thr.printStackTrace();
185        } finally {
186          output_.close();
187        }
188      }
189    
190      public static void printUsage() {
191        output_.println("Usage: SignRaw <PKCS#11 module> <userPIN> <file to be signed> [<signature value file>]");
192        output_.println(" e.g.: SignRaw pk2priv.dll password data.dat.sha1 signature.bin");
193        output_.println("The given DLL must be in the search path of the system.");
194      }
195    
196    }