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.BufferedReader;
047    import java.io.InputStreamReader;
048    import java.io.PrintWriter;
049    import java.util.Arrays;
050    import java.util.List;
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.TokenInfo;
058    import iaik.pkcs.pkcs11.objects.GenericSecretKey;
059    
060    
061    /**
062     * This demo program shows how to generate secret keys.
063     *
064     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
065     * @version 0.1
066     * @invariants
067     */
068    public class GenerateKey {
069    
070      static PrintWriter output_;
071    
072      static BufferedReader input_;
073    
074      static {
075        try {
076          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
077          output_ = new PrintWriter(System.out, true);
078          input_ = new BufferedReader(new InputStreamReader(System.in));
079        } catch (Throwable thr) {
080          thr.printStackTrace();
081          output_ = new PrintWriter(System.out, true);
082          input_ = new BufferedReader(new InputStreamReader(System.in));
083        }
084      }
085    
086      public static void main(String[] args) {
087        if ((args.length != 1) && (args.length != 2)) {
088          printUsage();
089          System.exit(1);
090        }
091    
092        try {
093    
094          //Security.addProvider(new IAIK());
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          Slot selectedSlot = slots[0];
107          Token token = selectedSlot.getToken();
108          TokenInfo tokenInfo = token.getTokenInfo();
109    
110          output_.println("################################################################################");
111          output_.println("Information of Token:");
112          output_.println(tokenInfo);
113          output_.println("################################################################################");
114    
115          List supportedMechanisms = Arrays.asList(token.getMechanismList());
116    
117          Session session =
118              token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null);
119    
120          // if we have to user PIN login user
121          if (args.length == 2) {
122            session.login(Session.UserType.USER, args[1].toCharArray());
123          }
124    
125          if (supportedMechanisms.contains(Mechanism.GENERIC_SECRET_KEY_GEN)) {
126            output_.println("################################################################################");
127            output_.println("Generating generic secret key");
128    
129            Mechanism keyGenerationMechanism = (Mechanism) Mechanism.GENERIC_SECRET_KEY_GEN.clone();
130    
131            GenericSecretKey secretKeyTemplate = new GenericSecretKey();
132            secretKeyTemplate.getValueLen().setLongValue(new Long(16));
133    
134            GenericSecretKey secretKey =
135                (GenericSecretKey) session.generateKey(keyGenerationMechanism, secretKeyTemplate);
136    
137            output_.println("the secret key is");
138            output_.println(secretKey.toString());
139    
140            output_.println("################################################################################");
141          }
142          session.closeSession();
143          pkcs11Module.finalize(null);
144    
145        } catch (Throwable thr) {
146          thr.printStackTrace();
147        }
148      }
149    
150      public static void printUsage() {
151        output_.println("Usage: GenerateKey <PKCS#11 module> [<user-PIN>]");
152        output_.println(" e.g.: GenerateKey cryptoki.dll");
153        output_.println("The given DLL must be in the search path of the system.");
154      }
155    
156    }