KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > core > model > ca > catoken > BaseCAToken


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13
14  package org.ejbca.core.model.ca.catoken;
15
16 import java.security.InvalidKeyException JavaDoc;
17 import java.security.KeyPair JavaDoc;
18 import java.security.KeyStore JavaDoc;
19 import java.security.KeyStoreException JavaDoc;
20 import java.security.NoSuchAlgorithmException JavaDoc;
21 import java.security.PrivateKey JavaDoc;
22 import java.security.Provider JavaDoc;
23 import java.security.PublicKey JavaDoc;
24 import java.security.Security JavaDoc;
25 import java.security.Signature JavaDoc;
26 import java.security.UnrecoverableKeyException JavaDoc;
27 import java.util.Hashtable JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.Properties JavaDoc;
30
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.log4j.Logger;
33 import org.ejbca.core.model.InternalResources;
34 import org.ejbca.core.model.SecConst;
35
36
37 /**
38  * @author lars
39  * @version $Id: BaseCAToken.java,v 1.11.2.1 2007/06/15 09:07:50 jeklund Exp $
40  */

41 public abstract class BaseCAToken implements IHardCAToken {
42
43     /** Log4j instance */
44     private static final Logger log = Logger.getLogger(BaseCAToken.class);
45     /** Internal localization of logs and errors */
46     private static final InternalResources intres = InternalResources.getInstance();
47
48     final private String JavaDoc sProviderName;
49     final private String JavaDoc sSlotLabelKey;
50
51     /** The constructor of HardCAToken should throw an InstantiationException if the token can not
52      * be created, if for example depending jar files for the particular HSM is not available.
53      *
54      * @throws InstantiationException if the nCipher provider is not available
55      */

56     public BaseCAToken(String JavaDoc providerClassName, String JavaDoc pn,
57                        String JavaDoc slk) throws InstantiationException JavaDoc, IllegalAccessException JavaDoc {
58         log.debug("Creating CAToken");
59         sProviderName = pn;
60         sSlotLabelKey = slk;
61         try {
62             Provider JavaDoc prov = (Provider JavaDoc)Class.forName(providerClassName).newInstance();
63             Security.addProvider( prov );
64         } catch (ClassNotFoundException JavaDoc e) {
65             throw new InstantiationException JavaDoc("Class not found: "+providerClassName);
66         }
67     }
68
69     private KeyStrings keyStrings;
70     protected String JavaDoc sSlotLabel;
71     private Map JavaDoc mKeys;
72     private String JavaDoc mAuthCode;
73
74     private void autoActivate() {
75         if ( mKeys==null && mAuthCode!=null )
76             try {
77                 activate(mAuthCode);
78             } catch (Exception JavaDoc e) {
79                 log.debug(e);
80             }
81     }
82     private void testKey( KeyPair JavaDoc pair ) throws Exception JavaDoc {
83         final byte input[] = "Lillan gick p� v�gen ut, m�tte d�r en katt ...".getBytes();
84         final byte signBV[];
85         String JavaDoc keyalg = pair.getPublic().getAlgorithm();
86         if (log.isDebugEnabled()) {
87             log.debug("Testing keys with algorithm: "+keyalg);
88         }
89         String JavaDoc testSigAlg = "SHA1withRSA";
90         if (StringUtils.equals(keyalg, "EC")) {
91             testSigAlg = "SHA1withECDSA";
92         }
93         {
94             Signature JavaDoc signature = Signature.getInstance(testSigAlg, getProvider());
95             signature.initSign( pair.getPrivate() );
96             signature.update( input );
97             signBV = signature.sign();
98         }{
99             Signature JavaDoc signature = Signature.getInstance(testSigAlg, "BC");
100             signature.initVerify(pair.getPublic());
101             signature.update(input);
102             if ( !signature.verify(signBV) )
103                 throw new InvalidKeyException JavaDoc("Not possible to sign and then verify with key pair.");
104         }
105     }
106     /**
107      * @param keyStore
108      * @param authCode
109      * @throws Exception
110      */

111     protected void setKeys(KeyStore JavaDoc keyStore, String JavaDoc authCode) throws Exception JavaDoc {
112         mKeys = null;
113         final String JavaDoc keyAliases[] = keyStrings.getAllStrings();
114         final Map JavaDoc mTmp = new Hashtable JavaDoc();
115         for ( int i=0; i<keyAliases.length; i++ ) {
116             PrivateKey JavaDoc privateK =
117                 (PrivateKey JavaDoc)keyStore.getKey(keyAliases[i],
118                                             (authCode!=null && authCode.length()>0)? authCode.toCharArray():null);
119             PublicKey JavaDoc publicK = readPublicKey(keyStore, keyAliases[i]);
120             KeyPair JavaDoc keyPair = new KeyPair JavaDoc(publicK, privateK);
121             mTmp.put(keyAliases[i], keyPair);
122         }
123         for ( int i=0; i<keyAliases.length; i++ ) {
124             KeyPair JavaDoc pair = (KeyPair JavaDoc)mTmp.get(keyAliases[i]);
125             testKey(pair);
126             log.debug("Key with alias "+keyAliases[i]+" tested. toString for private part: "+pair.getPrivate());
127         }
128         mKeys = mTmp;
129         if ( getCATokenStatus()!=IHardCAToken.STATUS_ACTIVE )
130             throw new Exception JavaDoc("Activation test failed");
131     }
132
133     /**
134      * @param keyStore
135      * @param alias
136      * @return
137      * @throws KeyStoreException
138      * @throws NoSuchAlgorithmException
139      * @throws UnrecoverableKeyException
140      */

141     protected PublicKey JavaDoc readPublicKey(KeyStore JavaDoc keyStore, String JavaDoc alias) throws KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, UnrecoverableKeyException JavaDoc {
142         return keyStore.getCertificate(alias).getPublicKey();
143     }
144
145     /* (non-Javadoc)
146      * @see org.ejbca.core.model.ca.catoken.IHardCAToken#init(java.util.Properties, java.lang.String)
147      */

148     public void init(Properties JavaDoc properties, String JavaDoc signaturealgorithm) {
149         log.debug("Properties: "+(properties!=null ? properties.toString() : "null")+". Signaturealg: "+signaturealgorithm);
150         keyStrings = new KeyStrings(properties);
151         sSlotLabel = properties.getProperty(sSlotLabelKey);
152         sSlotLabel = sSlotLabel!=null ? sSlotLabel.trim() : null;
153         mAuthCode = properties.getProperty("pin");
154         autoActivate();
155     }
156
157     /* (non-Javadoc)
158      * @see org.ejbca.core.model.ca.catoken.IHardCAToken#activate(java.lang.String)
159      */

160     public abstract void activate(String JavaDoc authCode) throws CATokenOfflineException, CATokenAuthenticationFailedException;
161     
162     /* (non-Javadoc)
163      * @see org.ejbca.core.model.ca.catoken.IHardCAToken#deactivate()
164      */

165     public boolean deactivate(){
166         String JavaDoc msg = intres.getLocalizedMessage("catoken.deactivate");
167         log.info(msg);
168         mKeys = null;
169         return true;
170     }
171
172     /* (non-Javadoc)
173      * @see org.ejbca.core.model.ca.catoken.IHardCAToken#getPrivateKey(int)
174      */

175     public PrivateKey JavaDoc getPrivateKey(int purpose)
176         throws CATokenOfflineException {
177         autoActivate();
178         KeyPair JavaDoc keyPair = mKeys!=null ?
179             (KeyPair JavaDoc)mKeys.get(keyStrings.getString(purpose)) :
180             null;
181         if ( keyPair==null )
182             throw new CATokenOfflineException("no such key");
183         return keyPair.getPrivate();
184     }
185
186     /* (non-Javadoc)
187      * @see org.ejbca.core.model.ca.catoken.IHardCAToken#getPublicKey(int)
188      */

189     public PublicKey JavaDoc getPublicKey(int purpose)
190         throws CATokenOfflineException {
191         autoActivate();
192         KeyPair JavaDoc keyPair = mKeys!=null ?
193             (KeyPair JavaDoc)mKeys.get(keyStrings.getString(purpose)) :
194             null;
195         if ( keyPair==null )
196             throw new CATokenOfflineException();
197         return keyPair.getPublic();
198     }
199
200     /* (non-Javadoc)
201      * @see org.ejbca.core.model.ca.catoken.IHardCAToken#getProvider()
202      */

203     public String JavaDoc getProvider() {
204         return sProviderName;
205     }
206
207     /* (non-Javadoc)
208      * @see org.ejbca.core.model.ca.caadmin.IHardCAToken#getCATokenStatus()
209      */

210     public int getCATokenStatus() {
211         autoActivate();
212         {
213             String JavaDoc strings[] = keyStrings.getAllStrings();
214             int i=0;
215             while( strings!=null && i<strings.length && mKeys!=null && mKeys.get(strings[i])!=null )
216                 i++;
217             if ( strings==null || i<strings.length)
218                 return IHardCAToken.STATUS_OFFLINE;
219         } {
220             PrivateKey JavaDoc privateKey;
221             PublicKey JavaDoc publicKey;
222             try {
223                 privateKey = getPrivateKey(SecConst.CAKEYPURPOSE_KEYTEST);
224                 publicKey = getPublicKey(SecConst.CAKEYPURPOSE_KEYTEST);
225             } catch (CATokenOfflineException e) {
226                 privateKey = null;
227                 publicKey = null;
228                 log.debug("no test key defined");
229             }
230             if ( privateKey!=null && publicKey!=null ) {
231                 //Check that that the testkey is usable by doing a test signature.
232
try{
233                     testKey(new KeyPair JavaDoc(publicKey, privateKey));
234                 } catch( Throwable JavaDoc th ){
235                     log.error("Error testing activation", th);
236                     return IHardCAToken.STATUS_OFFLINE;
237                 }
238             }
239         }
240         return IHardCAToken.STATUS_ACTIVE;
241     }
242 }
243
Popular Tags