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.ByteArrayInputStream;
048    import java.io.InputStreamReader;
049    import java.io.PrintWriter;
050    import java.security.cert.CertificateFactory;
051    import java.security.cert.X509Certificate;
052    
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.Data;
059    import iaik.pkcs.pkcs11.objects.HardwareFeature;
060    import iaik.pkcs.pkcs11.objects.Object;
061    import iaik.pkcs.pkcs11.objects.PrivateKey;
062    import iaik.pkcs.pkcs11.objects.PublicKey;
063    import iaik.pkcs.pkcs11.objects.SecretKey;
064    import iaik.pkcs.pkcs11.objects.X509PublicKeyCertificate;
065    
066    
067    
068    /**
069     * This demo program is similar to GetInfo. It takes the first token and dumps
070     * all objects on this token.
071     *
072     * @author <a href="mailto:Karl.Scheibelhofer@iaik.at"> Karl Scheibelhofer </a>
073     * @version 0.1
074     * @invariants
075     */
076    public class ReadObjects {
077    
078      static PrintWriter output_;
079    
080      static BufferedReader input_;
081    
082      static {
083        try {
084          //output_ = new PrintWriter(new FileWriter("GetInfo_output.txt"), true);
085          output_ = new PrintWriter(System.out, true);
086          input_ = new BufferedReader(new InputStreamReader(System.in));
087        } catch (Throwable thr) {
088          thr.printStackTrace();
089          output_ = new PrintWriter(System.out, true);
090          input_ = new BufferedReader(new InputStreamReader(System.in));
091        }
092      }
093    
094      public static void main(String[] args) {
095        try {
096          if ((args.length == 1) || (args.length == 2)) {
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              System.out.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    
113            TokenInfo tokenInfo = token.getTokenInfo();
114            if (tokenInfo.isLoginRequired()) {
115              if (tokenInfo.isProtectedAuthenticationPath()) {
116                session.login(Session.UserType.USER, null); // the token prompts the PIN by other means; e.g. PIN-pad
117              } else {
118                output_.print("Enter user-PIN or press [return] to list just public objects: ");
119                output_.flush();
120                String userPINString = input_.readLine();
121                output_.println();
122                output_.print("listing all" + ((userPINString.length() > 0) ? "" : " public") + " objects on token");
123                if (userPINString.length() > 0) {
124                  // login user
125                  session.login(Session.UserType.USER, userPINString.toCharArray());
126                }
127              }
128            }
129    
130            output_.println("################################################################################");
131            output_.println("listing all private keys");
132            PrivateKey privateKeyTemplate = new PrivateKey();
133    
134            session.findObjectsInit(privateKeyTemplate);
135    
136            Object[] foundPrivateKeyObjects = session.findObjects(1); // find first
137    
138            while (foundPrivateKeyObjects.length > 0) {
139              output_.println("________________________________________________________________________________");
140              output_.println(foundPrivateKeyObjects[0]);
141              output_.println("________________________________________________________________________________");
142              foundPrivateKeyObjects = session.findObjects(1); //find next
143            }
144            session.findObjectsFinal();
145    
146            output_.println("################################################################################");
147    
148            output_.println("################################################################################");
149            output_.println("listing all public keys");
150            PublicKey publicKeyTemplate = new PublicKey();
151    
152            session.findObjectsInit(publicKeyTemplate);
153    
154            Object[] foundPublicKeyObjects = session.findObjects(1); // find first
155    
156            while (foundPublicKeyObjects.length > 0) {
157              output_.println("________________________________________________________________________________");
158              output_.println(foundPublicKeyObjects[0]);
159              output_.println("________________________________________________________________________________");
160              foundPublicKeyObjects = session.findObjects(1); //find next
161            }
162            session.findObjectsFinal();
163    
164            output_.println("################################################################################");
165    
166            output_.println("################################################################################");
167            output_.println("listing all X.509 public key certificates");
168            X509PublicKeyCertificate x509PublicKeyCertificateTemplate = new X509PublicKeyCertificate();
169    
170            session.findObjectsInit(x509PublicKeyCertificateTemplate);
171    
172            Object[] foundTokenObjects = session.findObjects(1); // find first
173    
174            while (foundTokenObjects.length > 0) {
175              output_.println("________________________________________________________________________________");
176              output_.println(foundTokenObjects[0]);
177              output_.println("--------------------------------------------------------------------------------");
178              X509PublicKeyCertificate x509PublicKeyCertificate = (X509PublicKeyCertificate) foundTokenObjects[0];
179              CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
180              byte[] derEncodedCertificate = x509PublicKeyCertificate.getValue().getByteArrayValue();
181              X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(
182                  new ByteArrayInputStream(derEncodedCertificate));
183              output_.println(x509Certificate);
184              output_.println("________________________________________________________________________________");
185              foundTokenObjects = session.findObjects(1); //find next
186            }
187            session.findObjectsFinal();
188    
189            output_.println("################################################################################");
190    
191            output_.println("################################################################################");
192            output_.println("listing all secret keys");
193            SecretKey secretKeyTemplate = new SecretKey();
194    
195            session.findObjectsInit(secretKeyTemplate);
196    
197            Object[] foundSecretKeyObjects = session.findObjects(1); // find first
198    
199            while (foundSecretKeyObjects.length > 0) {
200              output_.println("________________________________________________________________________________");
201              output_.println(foundSecretKeyObjects[0]);
202              output_.println("________________________________________________________________________________");
203              foundSecretKeyObjects = session.findObjects(1); //find next
204            }
205            session.findObjectsFinal();
206    
207            output_.println("################################################################################");
208    
209            output_.println("################################################################################");
210            output_.println("listing all data objects");
211            Data dataTemplate = new Data();
212    
213            session.findObjectsInit(dataTemplate);
214    
215            Object[] foundDataObjects = session.findObjects(1); // find first
216    
217            while (foundDataObjects.length > 0) {
218              output_.println("________________________________________________________________________________");
219              output_.println(foundDataObjects[0]);
220              output_.println("________________________________________________________________________________");
221              foundDataObjects = session.findObjects(1); //find next
222            }
223            session.findObjectsFinal();
224    
225            output_.println("################################################################################");
226    
227            output_.println("################################################################################");
228            output_.println("listing all hardware feature objects");
229            HardwareFeature hardwareFeatureTemplate = new HardwareFeature();
230    
231            session.findObjectsInit(hardwareFeatureTemplate);
232    
233            Object[] foundHardwareFeatureObjects = session.findObjects(1); // find first
234    
235            while (foundHardwareFeatureObjects.length > 0) {
236              output_.println("________________________________________________________________________________");
237              output_.println(foundHardwareFeatureObjects[0]);
238              output_.println("________________________________________________________________________________");
239              foundHardwareFeatureObjects = session.findObjects(1); //find next
240            }
241            session.findObjectsFinal();
242    
243            output_.println("################################################################################");
244    
245            session.closeSession();
246    
247            pkcs11Module.finalize(null);
248    
249          } else {
250            printUsage();
251          }
252        } catch (Throwable ex) {
253          ex.printStackTrace();
254        }
255      }
256    
257      protected static void printUsage() {
258        output_.println("ReadObjects <PKCS#11 module name>");
259        output_.println("e.g.: ReadObjects pk2priv.dll");
260      }
261    
262    }