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    
050    import iaik.pkcs.pkcs11.Module;
051    import iaik.pkcs.pkcs11.Session;
052    import iaik.pkcs.pkcs11.Token;
053    import iaik.pkcs.pkcs11.TokenInfo;
054    
055    
056    
057    /**
058     * This program initializes a token. Note that this erases all data on the
059     * token.
060     *
061     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
062     * @version 0.1
063     * @invariants
064     */
065    public class InitToken {
066    
067      static PrintWriter output_;
068    
069      static BufferedReader input_;
070    
071      static {
072        try {
073          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
074          output_ = new PrintWriter(System.out, true);
075          input_ = new BufferedReader(new InputStreamReader(System.in));
076        } catch (Throwable thr) {
077          thr.printStackTrace();
078          output_ = new PrintWriter(System.out, true);
079          input_ = new BufferedReader(new InputStreamReader(System.in));
080        }
081      }
082    
083      public static void main(String[] args) {
084        if (args.length != 2) {
085          printUsage();
086          System.exit(1);
087        }
088    
089        try {
090    
091            Module pkcs11Module = Module.getInstance(args[0]);
092            pkcs11Module.initialize(null);
093    
094            Token token = Util.selectToken(pkcs11Module, output_, input_);
095            if (token == null) {
096              output_.println("We have no token to proceed. Finished.");
097              output_.flush();
098              System.exit(0);
099            }
100    
101            TokenInfo tokenInfo = token.getTokenInfo();
102    
103            output_.println("################################################################################");
104            output_.println("Information of Token to be initialized:");
105            output_.println(tokenInfo);
106            output_.println("################################################################################");
107    
108    /*      
109            output_.println("################################################################################");
110            output_.println("ATTENTION! Initialization will start in 10 seconds. You have time to remove the token or press any key to abort. Countdown... ");
111    
112            InputStreamReader inputReader = new InputStreamReader(System.in);
113            for (int i = 10; i >= 0; i--) {
114              output_.print("\r");
115              output_.print(i);
116              output_.print(' ');
117              output_.flush();
118              Thread.sleep(1000);
119              if (inputReader.ready()) {
120                output_.println("Aborted...EXIT");
121                output_.flush();
122                pkcs11Module.finalize(null);
123                System.exit(0);
124              }
125            }
126            output_.println();
127     */
128            output_.print("initializing... ");
129    
130            String soPINString = null;
131            if (tokenInfo.isProtectedAuthenticationPath()) {
132              output_.print("Please enter the SO-PIN at the PIN-pad of your reader.");
133              token.initToken(null, args[1]);; // the token prompts the PIN by other means; e.g. PIN-pad
134            } else {
135              output_.print("Enter the SO-PIN and press [return key]: ");
136              output_.flush();
137              soPINString = input_.readLine();
138              token.initToken(soPINString.toCharArray(), args[1]);
139            }
140            output_.println("FINISHED");
141    
142            // login security officer
143            if (tokenInfo.isLoginRequired()) {
144              output_.print("initializing user-PIN... ");
145              Session session =
146                  token.openSession(Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null);
147    
148              if (tokenInfo.isProtectedAuthenticationPath()) {
149                output_.print("Please enter the SO-PIN at the PIN-pad of your reader.");
150                output_.flush();
151                session.login(Session.UserType.SO, null); // the token prompts the PIN by other means; e.g. PIN-pad
152                output_.print("Please enter the user-PIN at the PIN-pad of your reader.");
153                output_.flush();
154                session.initPIN(null);
155              } else {
156                if (soPINString != null) {
157                  session.login(Session.UserType.SO, soPINString.toCharArray());
158                } else {
159                  output_.print("Enter the SO-PIN and press [return key]: ");
160                  output_.flush();
161                  soPINString = input_.readLine();
162                  session.login(Session.UserType.SO, soPINString.toCharArray());
163                }
164                output_.print("Enter the user-PIN and press [return key]: ");
165                output_.flush();
166                String userPINString = input_.readLine();
167                session.initPIN(userPINString.toCharArray());
168              }
169              session.closeSession();
170              output_.println("FINISHED");
171            }
172    
173            output_.println("################################################################################");
174    
175            tokenInfo = token.getTokenInfo();
176    
177            output_.println("################################################################################");
178            output_.println("Information of initialized Token:");
179            output_.println(tokenInfo);
180            output_.println("################################################################################");
181    
182            pkcs11Module.finalize(null);
183    
184        } catch (Throwable thr) {
185          thr.printStackTrace();
186        }
187      }
188    
189      public static void printUsage() {
190        output_.println("Usage: InitToken <PKCS#11 module> \"Card Label\"");
191        output_.println(" e.g.: InitToken pk2priv.dll \"My Test Card\"");
192        output_.println("ATTENTION: Any data on the card will get lost upon initialization!");
193        output_.println("The given DLL must be in the search path of the system.");
194      }
195    
196    }