download PKCS11Signer.java
Language: Java
Copyright: (C) 2005 eMayor Consortium (http://www.emayor.org) (C) 2005 Advanced Encryption Technology Europe B.V.
LOC: 224
Project Info
eMayor
Server: BerliOS
Type: cvs
...lient\controlers\xmlsigner\
   Base64EncodedData.java
   ...lIDSelectionDialog.java
   EMayorDocFunctions.java
   FormReader.java
   FormWriter.java
   IAIKPkcs11.properties
   PKCS11Signer.java
   Signable.java
   Signer.java
   SignerException.java
   SignerFactory.java
   XMLBlob.java
   XMLSigner.java
   ...gner_eMayorVersion.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//==============================================================================
// Copyright (C) 2005 Advanced Encryption Technology Europe B.V.
// Copyright (C) 2005 eMayor Consortium (http://www.emayor.org)
// All rights are reserved. Reproduction in whole or in part is prohibited
// without the written consent of the copyright owner.
//
// Package: org.emayor.xmlsigner
// Class:   PKCS11Signer
// Version: $Id: PKCS11Signer.java,v 1.1 2005/11/16 10:51:00 emayor Exp $
// Product: Java XML signing applet
//
// Description:
//		PKCS #11 based Signer implementation
//==============================================================================

package org.emayor.client.controlers.xmlsigner;

import iaik.pkcs.pkcs11.*;
import iaik.pkcs.pkcs11.objects.*;

public class PKCS11Signer extends SignerFactory implements Signer
{
    //==========================================================================
    // Member variables
    //==========================================================================
    
    // PKCS #11 module instance
    private Module				p11Module					= null;
    
    private Token				p11Token					= null;
    
    private Session				p11Session					= null;
    
    private RSAPrivateKey		p11PrivateSigningKey		= null;
    
    private byte[]				signingCertificate			= null;
    
    //==========================================================================
    // Constructors
    //==========================================================================
    
    private PKCS11Signer()
    {
        // Initialise the PKCS #11 library
        initialisePKCS11();
        
        try
        {
            // Find tokens
	        Slot[] slotsWithToken = p11Module.getSlotList(
	            Module.SlotRequirement.TOKEN_PRESENT);
	        
	        for (int i = 0; i < slotsWithToken.length; i++)
	        {
	            try
	            {
	                p11Token = slotsWithToken[i].getToken();
	                
	                p11Session = p11Token.openSession(
	                    Token.SessionType.SERIAL_SESSION,
	                    Token.SessionReadWriteBehavior.RW_SESSION,
	                    null,
	                    null);
	                
	                // Log in, if necessary
	                login();
	                
	                // Search for signing keys
	                RSAPrivateKey searchTemplate = new RSAPrivateKey();
	                searchTemplate.getSign().setBooleanValue(Boolean.TRUE);
	                
	                p11Session.findObjectsInit(searchTemplate);
	                
	                iaik.pkcs.pkcs11.objects.Object[] foundObjects = 
	                    p11Session.findObjects(1);
	                
	                p11Session.findObjectsFinal();
	                
	                if ((foundObjects == null) || (foundObjects.length == 0))
	                {
	                    continue;
	                }
	                
	                // Found a signing key, we're ready!
	                p11PrivateSigningKey = (RSAPrivateKey) foundObjects[0];
	                
	                System.out.println("Found a suitable signing key on the token with the following label: ");
	                
	                TokenInfo tokenInfo = p11Token.getTokenInfo();
	                
	                System.out.println("\"" + tokenInfo.getLabel() + "\"");
	                
	                return;
	            }
	            catch (TokenException te)
	            {
	                continue;
	            }
	        }
        }
        catch (TokenException te)
        {
            // The signer exception is thrown below
        }
        
        throw new SignerException
        (
            "Unable to find a token or suitable key-pair"
        );
    }
    
    private PKCS11Signer(byte[] searchCriterium, int criterium)
    {
        // Initialise the PKCS #11 library
        initialisePKCS11();
        
        try
        {
            // Find tokens
	        Slot[] slotsWithToken = p11Module.getSlotList(
	            Module.SlotRequirement.TOKEN_PRESENT);
	        
	        for (int i = 0; i < slotsWithToken.length; i++)
	        {
	            try
	            {
	                p11Token = slotsWithToken[i].getToken();
	                
	                p11Session = p11Token.openSession(
	                    Token.SessionType.SERIAL_SESSION,
	                    Token.SessionReadWriteBehavior.RW_SESSION,
	                    null,
	                    null);
	                
	                // Log in, if necessary
	                login();
	                
	                // Search for certificates based on the specified
	                // criterium
	                X509PublicKeyCertificate certificateSearch =
	                    new X509PublicKeyCertificate();
	                /*
	                	                
	                switch(criterium)
	                {
	                case SignerFactory.SEARCH_SUBJECT:
	                    certificateSearch.getSubject().setByteArrayValue(
	                        searchCriterium);
	                	break;
	                case SignerFactory.SEARCH_ISSUER:
	                    certificateSearch.getIssuer().setByteArrayValue(
		                        searchCriterium);
		               	break;
	                case SignerFactory.SEARCH_ID:
	                    certificateSearch.getId().setByteArrayValue(
		                        searchCriterium);
		                break;
	                }
	                */
	                p11Session.findObjectsInit(certificateSearch);
	                
	                iaik.pkcs.pkcs11.objects.Object[] foundObjects = 
	                    p11Session.findObjects(1);
	                
	                p11Session.findObjectsFinal();
	                
	                if ((foundObjects == null) || (foundObjects.length == 0))
	                {
	                    continue;
	                }
	                
	                X509PublicKeyCertificate certificate =
	                    (X509PublicKeyCertificate) foundObjects[0];
	                
	                // A certificate was found, find the matching private key
	                RSAPrivateKey searchTemplate = new RSAPrivateKey();
	                searchTemplate.getId().setByteArrayValue(
	                    certificate.getId().getByteArrayValue());
	                
	                p11Session.findObjectsInit(searchTemplate);
	                
	                foundObjects = p11Session.findObjects(1);
	                
	                p11Session.findObjectsFinal();
	                
	                if ((foundObjects == null) || (foundObjects.length == 0))
	                {
	                    continue;
	                }
	                
	                // Found a signing key, we're ready!
	                p11PrivateSigningKey = (RSAPrivateKey) foundObjects[0];
	                
	                System.out.println("Found a specific signing key based on the search criteria on the token with the following label:");
	                
	                TokenInfo tokenInfo = p11Token.getTokenInfo();
	                
	                System.out.println("\"" + tokenInfo.getLabel() + "\"");
	                
	                // Store the signing certificate
	                signingCertificate = 
	                    certificate.getValue().getByteArrayValue();
	                
	                return;
	            }
	            catch (TokenException te)
	            {
	                continue;
	            }
	        }
        }
        catch (TokenException te)
        {
            // The signer exception is thrown below
        }
        
        throw new SignerException
        (
            "Unable to find a token or suitable key-pair"
        );
    }
    
    //==========================================================================
    // Initialise the PKCS #11 library
    //==========================================================================
    
    private void initialisePKCS11()
    {
        // Get an instance of the PKCS #11 module
        try
        {
            // Load AET PKCS #11 module
            p11Module = Module.getInstance("aetpkssw.dll");
            
            p11Module.initialize(null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            
            throw new SignerException
            	(
            	    "Unable to get a reference to the PKCS #11 library"
            	);
        }
    }
    
    //==========================================================================
    // Login if required
    //==========================================================================
    
    private void login()
    {
        try
        {
            TokenInfo tokenInfo = p11Token.getTokenInfo();
            
            if (tokenInfo.isLoginRequired())
            {
                p11Session.login(Session.UserType.USER, null);
            }
        }
        catch (TokenException te)
        {
            throw new SignerException("Failed to log in to the token");
        }
    }
    
    //==========================================================================
    // Finalise the object
    //==========================================================================
    
    protected void finalize()
    {
        if (p11Module != null)
        {
            try
            {
                // Finalise the PKCS #11 library
                p11Module.finalize(null);
            }
            catch (Exception e)
            {
            }
        }
    }
    
    //==========================================================================
    // Sign the specified signable object
    //==========================================================================
    
    public byte[] sign(Signable signable)
    {
        // Retrieve the canonical representation of the signable object
        byte[] data = signable.getCanonicalEncoding();
        
        byte[] signature = null;
        
        try
        {
            // Sign the data
            p11Session.signInit(
                Mechanism.SHA1_RSA_PKCS, p11PrivateSigningKey);
            
            signature = p11Session.sign(data);
        }
        catch (TokenException te)
        {
            throw new SignerException("Failed to sign the supplied data");
        }
        
        return signature;
    }
    
    //==========================================================================
    // Digest the specified signable object
    //==========================================================================
    
    public byte[] digest(Signable signable)
    {
        // Retrieve the canonical representation of the signable object
        byte[] data = signable.getCanonicalEncoding();
        
        byte[] digest = null;
        
        try
        {
            // Digest the data
            p11Session.digestInit(Mechanism.SHA_1);
            
            digest = p11Session.digest(data);
        }
        catch (TokenException te)
        {
            throw new SignerException("Failed to digest the supplied data");
        }
        
        return digest;
    }
    
    //==========================================================================
    // Return the signing certificate (if any)
    //==========================================================================
    
    public byte[] getSigningCertificate()
    {
        return signingCertificate;
    }
    
    //==========================================================================
    // Return the modulus of the signing key
    //==========================================================================
    
    public byte[] getSigningKeyModulus()
    {
        if (p11PrivateSigningKey != null)
        {
            return p11PrivateSigningKey.getModulus().getByteArrayValue();
        }
        
        return null;
    }
    
    //==========================================================================
    // Return the exponent of the signing key
    //==========================================================================
    
    public byte[] getSigningKeyExponent()
    {
        if (p11PrivateSigningKey != null)
        {
            return p11PrivateSigningKey.getPublicExponent().getByteArrayValue();
        }
        
        return null;
    }

    //==========================================================================
    // Retrieve a signer instance. In this case, a signer based on the first
    // available key-pair on the token will be returned
    //==========================================================================

    public static Signer getInstance()
    {
        return new PKCS11Signer();
    }

    //==========================================================================
    // Retrieve a signer instance. In this case, a signer based on the first
    // available key-pair belonging to the certificate matching the search
    // criteria will be returned
    //==========================================================================
    
    public static Signer getInstance(byte[] searchCriterium, int criterium)
    {
        return new PKCS11Signer(searchCriterium, criterium);
    }
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us