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 iaik.pkcs.pkcs11.Mechanism;
047    import iaik.pkcs.pkcs11.Module;
048    import iaik.pkcs.pkcs11.Session;
049    import iaik.pkcs.pkcs11.Slot;
050    import iaik.pkcs.pkcs11.Token;
051    import iaik.pkcs.pkcs11.TokenInfo;
052    import iaik.pkcs.pkcs11.objects.KeyPair;
053    import iaik.pkcs.pkcs11.objects.RSAPrivateKey;
054    import iaik.pkcs.pkcs11.objects.RSAPublicKey;
055    import iaik.pkcs.pkcs11.wrapper.Functions;
056    
057    import java.io.BufferedReader;
058    import java.io.InputStreamReader;
059    import java.io.PrintWriter;
060    import java.util.Random;
061    
062    
063    
064    /**
065     * This demo program generates a 4096 bit RSA key-pair on the token and signs some data with it.
066     *
067     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
068     * @version 0.1
069     * @invariants
070     */
071    public class GenerateAndSign4096 {
072    
073      static BufferedReader input_;
074    
075      static PrintWriter output_;
076    
077      static {
078        try {
079          output_ = new PrintWriter(System.out, true);
080          input_ = new BufferedReader(new InputStreamReader(System.in));
081        } catch (Throwable thr) {
082          thr.printStackTrace();
083          output_ = new PrintWriter(System.out, true);
084          input_ = new BufferedReader(new InputStreamReader(System.in));
085       }
086      }
087    
088      public static void main(String[] args) {
089        if (args.length != 2) {
090          printUsage();
091          System.exit(1);
092        }
093    
094        try {
095    
096          Module pkcs11Module = Module.getInstance(args[0]);
097          pkcs11Module.initialize(null);
098    
099          Slot[] slots = pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT);
100    
101          if (slots.length == 0) {
102            output_.println("No slot with present token found!");
103            System.exit(0);
104          }
105    
106          int slotIndex = Integer.parseInt(args[1]);
107          Slot selectedSlot = slots[slotIndex];
108          Token token = selectedSlot.getToken();
109          TokenInfo tokenInfo = token.getTokenInfo();
110    
111          output_.println("################################################################################");
112          output_.println("Information of Token:");
113          output_.println(tokenInfo);
114          output_.println("################################################################################");
115    
116          Session session = Util.openAuthorizedSession(token, Token.SessionReadWriteBehavior.RW_SESSION, output_, input_);
117              // token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null);
118    
119          output_.println("################################################################################");
120          int keySize = 4096;
121          output_.print("Generating new " + keySize + " bit RSA key-pair... ");
122          output_.flush();
123    
124          Mechanism keyPairGenerationMechanism = Mechanism.RSA_PKCS_KEY_PAIR_GEN;
125          RSAPublicKey rsaPublicKeyTemplate = new RSAPublicKey();
126          RSAPrivateKey rsaPrivateKeyTemplate = new RSAPrivateKey();
127    
128          // set the general attributes for the public key
129          rsaPublicKeyTemplate.getModulusBits().setLongValue(new Long(keySize));
130          byte[] publicExponentBytes = {0x01, 0x00, 0x01}; // 2^16 + 1
131          rsaPublicKeyTemplate.getPublicExponent().setByteArrayValue(publicExponentBytes);
132          rsaPublicKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
133          byte[] id = new byte[20];
134          new Random().nextBytes(id);
135          rsaPublicKeyTemplate.getId().setByteArrayValue(id);
136          //rsaPublicKeyTemplate.getLabel().setCharArrayValue(args[2].toCharArray());
137    
138          rsaPrivateKeyTemplate.getSensitive().setBooleanValue(Boolean.TRUE);
139          rsaPrivateKeyTemplate.getToken().setBooleanValue(Boolean.FALSE);
140          rsaPrivateKeyTemplate.getPrivate().setBooleanValue(Boolean.TRUE);
141          rsaPrivateKeyTemplate.getId().setByteArrayValue(id);
142          //rsaPrivateKeyTemplate.getLabel().setCharArrayValue(args[2].toCharArray());
143    
144          rsaPrivateKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);
145          rsaPublicKeyTemplate.getVerify().setBooleanValue(Boolean.TRUE);
146    
147          // netscape does not set these attribute, so we do no either
148          rsaPublicKeyTemplate.getKeyType().setPresent(false);
149          rsaPublicKeyTemplate.getObjectClass().setPresent(false);
150          rsaPrivateKeyTemplate.getKeyType().setPresent(false);
151          rsaPrivateKeyTemplate.getObjectClass().setPresent(false);
152    
153          KeyPair generatedKeyPair = session.generateKeyPair(keyPairGenerationMechanism, rsaPublicKeyTemplate, rsaPrivateKeyTemplate);
154          RSAPublicKey generatedRSAPublicKey = (RSAPublicKey) generatedKeyPair.getPublicKey();
155          RSAPrivateKey generatedRSAPrivateKey = (RSAPrivateKey) generatedKeyPair.getPrivateKey();
156          // no we may work with the keys...
157    
158          output_.println("Success");
159          output_.println("The public key is");
160          output_.println("_______________________________________________________________________________");
161          output_.println(generatedRSAPublicKey);
162          output_.println("_______________________________________________________________________________");
163          output_.println("The private key is");
164          output_.println("_______________________________________________________________________________");
165          output_.println(generatedRSAPrivateKey);
166          output_.println("_______________________________________________________________________________");
167    
168          output_.println("################################################################################");
169          output_.print("Signing Data... ");
170    
171          Mechanism signatureMechanism = Mechanism.RSA_PKCS;
172          session.signInit(signatureMechanism, generatedRSAPrivateKey);
173          byte[] dataToBeSigned = "12345678901234567890123456789012345".getBytes("ASCII");
174          byte[] signatureValue = session.sign(dataToBeSigned);
175          output_.println("Finished");
176          output_.println("Signature Value: " + Functions.toHexString(signatureValue));
177          output_.println("################################################################################");
178          
179          session.closeSession();
180          pkcs11Module.finalize(null);
181    
182        } catch (Throwable thr) {
183          thr.printStackTrace();
184        }
185      }
186    
187      public static void printUsage() {
188        output_.println("Usage: GenerateAndSign4096 <PKCS#11 module> <slot index>");
189        output_.println(" e.g.: GenerateAndSign4096 cs2_pkcs11.dll 3");
190        output_.println("The given DLL must be in the search path of the system.");
191      }
192    
193    }