001: /*************************************************************************
002: * *
003: * EJBCA: The OpenSource Certificate Authority *
004: * *
005: * This software is free software; you can redistribute it and/or *
006: * modify it under the terms of the GNU Lesser General Public *
007: * License as published by the Free Software Foundation; either *
008: * version 2.1 of the License, or any later version. *
009: * *
010: * See terms of license at gnu.org. *
011: * *
012: *************************************************************************/package org.ejbca.ui.cli.batch;
013:
014: import java.io.File;
015: import java.io.FileOutputStream;
016: import java.io.IOException;
017: import java.rmi.RemoteException;
018: import java.security.GeneralSecurityException;
019: import java.security.KeyPair;
020: import java.security.KeyStore;
021: import java.security.KeyStoreException;
022: import java.security.NoSuchAlgorithmException;
023: import java.security.NoSuchProviderException;
024: import java.security.UnrecoverableKeyException;
025: import java.security.cert.Certificate;
026: import java.security.cert.CertificateException;
027: import java.security.cert.X509Certificate;
028: import java.util.ArrayList;
029: import java.util.Collection;
030: import java.util.Iterator;
031:
032: import javax.ejb.CreateException;
033: import javax.naming.Context;
034: import javax.naming.NamingException;
035:
036: import org.apache.log4j.Logger;
037: import org.ejbca.core.ejb.InitialContextBuilder;
038: import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionHome;
039: import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionRemote;
040: import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionHome;
041: import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionRemote;
042: import org.ejbca.core.ejb.ca.sign.ISignSessionHome;
043: import org.ejbca.core.ejb.ca.sign.ISignSessionRemote;
044: import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionHome;
045: import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionRemote;
046: import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
047: import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
048: import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionHome;
049: import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionRemote;
050: import org.ejbca.core.model.InternalResources;
051: import org.ejbca.core.model.SecConst;
052: import org.ejbca.core.model.ca.catoken.CATokenConstants;
053: import org.ejbca.core.model.keyrecovery.KeyRecoveryData;
054: import org.ejbca.core.model.log.Admin;
055: import org.ejbca.core.model.ra.UserAdminConstants;
056: import org.ejbca.core.model.ra.UserDataConstants;
057: import org.ejbca.core.model.ra.UserDataVO;
058: import org.ejbca.util.CertTools;
059: import org.ejbca.util.KeyTools;
060: import org.ejbca.util.P12toPEM;
061:
062: /**
063: * This class generates keys and request certificates for all users with status NEW. The result is
064: * generated PKCS12-files.
065: *
066: * @version $Id: BatchMakeP12.java,v 1.12 2007/05/15 21:00:16 jeklund Exp $
067: */
068: public class BatchMakeP12 {
069: /**
070: * For logging
071: */
072: private static final Logger log = Logger
073: .getLogger(BatchMakeP12.class);
074: /** Internal localization of logs and errors */
075: private static final InternalResources intres = InternalResources
076: .getInstance();
077:
078: BatchToolProperties props = new BatchToolProperties();
079:
080: /**
081: * Where created P12-files are stored, default username.p12
082: */
083: private String mainStoreDir = "";
084: private IUserAdminSessionHome adminhome;
085: private IRaAdminSessionHome raadminhome;
086: private ISignSessionHome signhome;
087: private ICAAdminSessionHome caadminhome;
088: private IKeyRecoverySessionHome keyrecoveryhome;
089: private IAuthenticationSessionHome authhome;
090: private Admin administrator;
091: private boolean usekeyrecovery = false;
092:
093: /**
094: * Gets an initial context
095: *
096: * @return new initial context
097: * @throws NamingException if we can't find jndi name
098: */
099: public static Context getInitialContext() throws NamingException {
100: log.debug(">GetInitialContext");
101:
102: // jndi.properties must exist in classpath
103: Context ctx = InitialContextBuilder.getInstance()
104: .getInitialContext();
105: log.debug("<GetInitialContext");
106:
107: return ctx;
108: }
109:
110: /**
111: * Creates new BatchMakeP12 object.
112: *
113: * @throws javax.naming.NamingException
114: * @throws CreateException
115: * @throws RemoteException
116: */
117: public BatchMakeP12() throws javax.naming.NamingException,
118: javax.ejb.CreateException, java.rmi.RemoteException,
119: java.io.IOException {
120: log.debug(">BatchMakeP12:");
121:
122: administrator = new Admin(Admin.TYPE_BATCHCOMMANDLINE_USER);
123:
124: // Bouncy Castle security provider
125: CertTools.installBCProvider();
126:
127: Context jndiContext = getInitialContext();
128: Object obj = jndiContext.lookup("UserAdminSession");
129: adminhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject
130: .narrow(obj, IUserAdminSessionHome.class);
131: obj = jndiContext.lookup("RaAdminSession");
132: raadminhome = (IRaAdminSessionHome) javax.rmi.PortableRemoteObject
133: .narrow(obj, IRaAdminSessionHome.class);
134: obj = jndiContext.lookup("RSASignSession");
135: signhome = (ISignSessionHome) javax.rmi.PortableRemoteObject
136: .narrow(obj, ISignSessionHome.class);
137: obj = jndiContext.lookup("CAAdminSession");
138: caadminhome = (ICAAdminSessionHome) javax.rmi.PortableRemoteObject
139: .narrow(obj, ICAAdminSessionHome.class);
140: obj = jndiContext.lookup("AuthenticationSession");
141: authhome = (IAuthenticationSessionHome) javax.rmi.PortableRemoteObject
142: .narrow(obj, IAuthenticationSessionHome.class);
143:
144: IRaAdminSessionRemote raadmin = raadminhome.create();
145: usekeyrecovery = (raadmin
146: .loadGlobalConfiguration(administrator))
147: .getEnableKeyRecovery();
148:
149: if (usekeyrecovery) {
150: obj = jndiContext.lookup("KeyRecoverySession");
151: keyrecoveryhome = (IKeyRecoverySessionHome) javax.rmi.PortableRemoteObject
152: .narrow(obj, IKeyRecoverySessionHome.class);
153: }
154:
155: log.debug("<BatchMakeP12:");
156: } // BatchMakeP12
157:
158: /**
159: * Gets full CA-certificate chain.
160: *
161: * @return Certificate[]
162: */
163: private Certificate[] getCACertChain(int caid) throws Exception {
164: log.debug(">getCACertChain()");
165:
166: ISignSessionRemote ss = signhome.create();
167: Certificate[] chain = (Certificate[]) ss.getCertificateChain(
168: administrator, caid).toArray(new Certificate[0]);
169: log.debug("<getCACertChain()");
170:
171: return chain;
172: } // getCACertificate
173:
174: /**
175: * Sets the location where generated P12-files will be stored, full name will be:
176: * mainStoreDir/username.p12.
177: *
178: * @param dir existing directory
179: */
180: public void setMainStoreDir(String dir) {
181: mainStoreDir = dir;
182: }
183:
184: /**
185: * Stores keystore.
186: *
187: * @param ks KeyStore
188: * @param username username, the owner of the keystore
189: * @param kspassword the password used to protect the peystore
190: * @param createJKS if a jks should be created
191: * @param createPEM if pem files should be created
192: * @throws IOException if directory to store keystore cannot be created
193: */
194: private void storeKeyStore(KeyStore ks, String username,
195: String kspassword, boolean createJKS, boolean createPEM)
196: throws IOException, KeyStoreException,
197: UnrecoverableKeyException, NoSuchAlgorithmException,
198: NoSuchProviderException, CertificateException {
199: log.debug(">storeKeyStore: ks=" + ks.toString() + ", username="
200: + username);
201:
202: // Where to store it?
203: if (mainStoreDir == null) {
204: throw new IOException(
205: "Can't find directory to store keystore in.");
206: }
207:
208: String keyStoreFilename = mainStoreDir + "/" + username;
209:
210: if (createJKS) {
211: keyStoreFilename += ".jks";
212: } else {
213: keyStoreFilename += ".p12";
214: }
215:
216: // If we should also create PEM-files, do that
217: if (createPEM) {
218: String PEMfilename = mainStoreDir + "/pem";
219: P12toPEM p12topem = new P12toPEM(ks, kspassword, true);
220: p12topem.setExportPath(PEMfilename);
221: p12topem.createPEM();
222: } else {
223: FileOutputStream os = new FileOutputStream(keyStoreFilename);
224: ks.store(os, kspassword.toCharArray());
225: }
226:
227: log.debug("Keystore stored in " + keyStoreFilename);
228: log.debug("<storeKeyStore: ks=" + ks.toString() + ", username="
229: + username);
230: } // storeKeyStore
231:
232: /**
233: * Creates files for a user, sends request to CA, receives reply and creates P12.
234: *
235: * @param username username
236: * @param password user's password
237: * @param id of CA used to issue the keystore certificates
238: * @param rsaKeys a previously generated RSA keypair
239: * @param createJKS if a jks should be created
240: * @param createPEM if pem files should be created
241: * @param savekeys if generated keys should be saved in db (key recovery)
242: * @param orgCert if an original key recovered cert should be reused, null indicates generate new cert.
243: * @throws Exception if the certificate is not an X509 certificate
244: * @throws Exception if the CA-certificate is corrupt
245: * @throws Exception if verification of certificate or CA-cert fails
246: * @throws Exception if keyfile (generated by ourselves) is corrupt
247: */
248:
249: private void createUser(String username, String password, int caid,
250: KeyPair rsaKeys, boolean createJKS, boolean createPEM,
251: boolean savekeys, X509Certificate orgCert) throws Exception {
252: log.debug(">createUser: username=" + username);
253:
254: // Send the certificate request to the CA
255: ISignSessionRemote ss = signhome.create();
256:
257: X509Certificate cert = null;
258:
259: if (orgCert != null) {
260: cert = orgCert;
261: ICAAdminSessionRemote caadminsession = caadminhome.create();
262: boolean finishUser = caadminsession.getCAInfo(
263: administrator, caid).getFinishUser();
264: if (finishUser) {
265: IAuthenticationSessionRemote authsession = authhome
266: .create();
267: authsession.finishUser(administrator, username,
268: password);
269: }
270:
271: } else {
272: // Create self signed certificate, because ECDSA keys are not serializable
273: String sigAlg = CATokenConstants.SIGALG_SHA1_WITH_RSA;
274: if (props.getKeyAlg().equals("ECDSA")) {
275: sigAlg = CATokenConstants.SIGALG_SHA256_WITH_ECDSA;
276: }
277: X509Certificate selfcert = CertTools.genSelfCert(
278: "CN=selfsigned", 1, null, rsaKeys.getPrivate(),
279: rsaKeys.getPublic(), sigAlg, false);
280: cert = (X509Certificate) ss.createCertificate(
281: administrator, username, password, selfcert);
282: }
283:
284: //System.out.println("issuer " + CertTools.getIssuerDN(cert) + ", " + cert.getClass().getName());
285: // Make a certificate chain from the certificate and the CA-certificate
286: Certificate[] cachain = getCACertChain(caid);
287: // Verify CA-certificate
288: if (CertTools
289: .isSelfSigned((X509Certificate) cachain[cachain.length - 1])) {
290: try {
291: cachain[cachain.length - 1]
292: .verify(cachain[cachain.length - 1]
293: .getPublicKey());
294: } catch (GeneralSecurityException se) {
295: String errMsg = intres
296: .getLocalizedMessage("batch.errorrootnotverify");
297: throw new Exception(errMsg);
298: }
299: } else {
300: String errMsg = intres
301: .getLocalizedMessage("batch.errorrootnotselfsigned");
302: throw new Exception(errMsg);
303: }
304:
305: // Verify that the user-certificate is signed by our CA
306: try {
307: cert.verify(cachain[0].getPublicKey());
308: } catch (GeneralSecurityException se) {
309: String errMsg = intres
310: .getLocalizedMessage("batch.errorgennotverify");
311: throw new Exception(errMsg);
312: }
313:
314: if (usekeyrecovery && savekeys) {
315: // Save generated keys to database.
316: IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome
317: .create();
318: keyrecoverysession.addKeyRecoveryData(administrator, cert,
319: username, rsaKeys);
320: }
321:
322: // Use CN if as alias in the keystore, if CN is not present use username
323: String alias = CertTools.getPartFromDN(CertTools
324: .getSubjectDN(cert), "CN");
325: if (alias == null)
326: alias = username;
327:
328: // Store keys and certificates in keystore.
329: KeyStore ks = null;
330:
331: if (createJKS) {
332: ks = KeyTools.createJKS(alias, rsaKeys.getPrivate(),
333: password, cert, cachain);
334: } else {
335: ks = KeyTools.createP12(alias, rsaKeys.getPrivate(), cert,
336: cachain);
337: }
338:
339: storeKeyStore(ks, username, password, createJKS, createPEM);
340: String iMsg = intres.getLocalizedMessage(
341: "batch.createkeystore", username);
342: log.info(iMsg);
343: log.debug("<createUser: username=" + username);
344: } // createUser
345:
346: /**
347: * Does the deed with one user...
348: *
349: * @param data user data for user
350: * @param createJKS if a jks should be created
351: * @param createPEM if pem files should be created
352: * @param keyrecoverflag if we should try to revoer already existing keys
353: * @throws Exception If something goes wrong...
354: */
355: private void processUser(UserDataVO data, boolean createJKS,
356: boolean createPEM, boolean keyrecoverflag) throws Exception {
357: KeyPair rsaKeys = null;
358: X509Certificate orgCert = null;
359:
360: if (usekeyrecovery && keyrecoverflag) {
361:
362: IRaAdminSessionRemote raadmin = raadminhome.create();
363: boolean reusecertificate = raadmin.getEndEntityProfile(
364: administrator, data.getEndEntityProfileId())
365: .getReUseKeyRevoceredCertificate();
366:
367: // Recover Keys
368: IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome
369: .create();
370: KeyRecoveryData recoveryData = keyrecoverysession
371: .keyRecovery(administrator, data.getUsername(),
372: data.getEndEntityProfileId());
373: if (reusecertificate) {
374: keyrecoverysession.unmarkUser(administrator, data
375: .getUsername());
376: }
377: if (recoveryData != null) {
378: rsaKeys = recoveryData.getKeyPair();
379: if (reusecertificate) {
380: orgCert = (X509Certificate) recoveryData
381: .getCertificate();
382: }
383: } else {
384: String errMsg = intres.getLocalizedMessage(
385: "batch.errornokeyrecoverydata", data
386: .getUsername());
387: throw new Exception(errMsg);
388: }
389: } else {
390: rsaKeys = KeyTools.genKeys(props.getKeySpec(), props
391: .getKeyAlg());
392: }
393: // Get certificate for user and create P12
394: if (rsaKeys != null) {
395: createUser(data.getUsername(), data.getPassword(), data
396: .getCAId(), rsaKeys, createJKS, createPEM,
397: !keyrecoverflag && data.getKeyRecoverable(),
398: orgCert);
399: }
400: } //processUser
401:
402: private boolean doCreate(IUserAdminSessionRemote admin,
403: UserDataVO data, int status) throws Exception {
404: boolean ret = false;
405: int tokentype = SecConst.TOKEN_SOFT_BROWSERGEN;
406: boolean createJKS = false;
407: boolean createPEM = false;
408: boolean createP12 = false;
409: // get users Token Type.
410: tokentype = data.getTokenType();
411: createP12 = tokentype == SecConst.TOKEN_SOFT_P12;
412: createPEM = tokentype == SecConst.TOKEN_SOFT_PEM;
413: createJKS = tokentype == SecConst.TOKEN_SOFT_JKS;
414:
415: // Only generate supported tokens
416: if (createP12 || createPEM || createJKS) {
417: if (status == UserDataConstants.STATUS_KEYRECOVERY) {
418: String iMsg = intres.getLocalizedMessage(
419: "batch.retrieveingkeys", data.getUsername());
420: log.info(iMsg);
421: } else {
422: String iMsg = intres.getLocalizedMessage(
423: "batch.generatingkeys", data.getUsername());
424: log.info(iMsg);
425: }
426:
427: // Grab new user, set status to INPROCESS
428: admin.setUserStatus(administrator, data.getUsername(),
429: UserDataConstants.STATUS_INPROCESS);
430: processUser(data, createJKS, createPEM,
431: (status == UserDataConstants.STATUS_KEYRECOVERY));
432:
433: // If all was OK , set status to GENERATED
434: admin.setUserStatus(administrator, data.getUsername(),
435: UserDataConstants.STATUS_GENERATED);
436:
437: // Delete clear text password
438: admin.setClearTextPassword(administrator, data
439: .getUsername(), null);
440: ret = true;
441: String iMsg = intres.getLocalizedMessage(
442: "batch.generateduser", data.getUsername());
443: log.info(iMsg);
444: } else {
445: log
446: .debug("Cannot batchmake browser generated token for user (wrong tokentype)- "
447: + data.getUsername());
448: }
449: return ret;
450: }
451:
452: /**
453: * Creates P12-files for all users with status NEW in the local database.
454: *
455: * @throws Exception if something goes wrong...
456: */
457: public void createAllNew() throws Exception {
458: log.debug(">createAllNew:");
459: String iMsg = intres.getLocalizedMessage(
460: "batch.generatingallstatus", "NEW");
461: log.info(iMsg);
462: createAllWithStatus(UserDataConstants.STATUS_NEW);
463: log.debug("<createAllNew:");
464: } // createAllNew
465:
466: /**
467: * Creates P12-files for all users with status FAILED in the local database.
468: *
469: * @throws Exception if something goes wrong...
470: */
471: public void createAllFailed() throws Exception {
472: log.debug(">createAllFailed:");
473: String iMsg = intres.getLocalizedMessage(
474: "batch.generatingallstatus", "FAILED");
475: log.info(iMsg);
476: createAllWithStatus(UserDataConstants.STATUS_FAILED);
477: log.debug("<createAllFailed:");
478: } // createAllFailed
479:
480: /**
481: * Creates P12-files for all users with status KEYRECOVER in the local database.
482: *
483: * @throws Exception if something goes wrong...
484: */
485: public void createAllKeyRecover() throws Exception {
486: if (usekeyrecovery) {
487: log.debug(">createAllKeyRecover:");
488: String iMsg = intres.getLocalizedMessage(
489: "batch.generatingallstatus", "KEYRECOVER");
490: log.info(iMsg);
491: createAllWithStatus(UserDataConstants.STATUS_KEYRECOVERY);
492: log.debug("<createAllKeyRecover:");
493: }
494: } // createAllKeyRecover
495:
496: /**
497: * Creates P12-files for all users with status in the local database.
498: *
499: * @param status
500: * @throws Exception if something goes wrong...
501: */
502: public void createAllWithStatus(int status) throws Exception {
503: log.debug(">createAllWithStatus: " + status);
504:
505: ArrayList result;
506: IUserAdminSessionRemote admin = adminhome.create();
507: boolean stopnow = false;
508:
509: //Collection result = admin.findAllUsersByStatus(administrator, status);
510: do {
511:
512: Collection queryResult = admin
513: .findAllUsersByStatusWithLimit(administrator,
514: status, true);
515: result = new ArrayList();
516:
517: Iterator iter = queryResult.iterator();
518: while (iter.hasNext()) {
519: UserDataVO data = (UserDataVO) iter.next();
520: if (data.getTokenType() == SecConst.TOKEN_SOFT_JKS
521: || data.getTokenType() == SecConst.TOKEN_SOFT_PEM
522: || data.getTokenType() == SecConst.TOKEN_SOFT_P12) {
523: result.add(data);
524: }
525: }
526:
527: String iMsg = intres.getLocalizedMessage(
528: "batch.generatingnoofusers", new Integer(result
529: .size()));
530: log.info(iMsg);
531:
532: int failcount = 0;
533: int successcount = 0;
534:
535: if (result.size() > 0) {
536: if (result.size() < UserAdminConstants.MAXIMUM_QUERY_ROWCOUNT) {
537: stopnow = true;
538: }
539: Iterator it = result.iterator();
540: String failedusers = "";
541: String successusers = "";
542: while (it.hasNext()) {
543: UserDataVO data = (UserDataVO) it.next();
544: if ((data.getPassword() != null)
545: && (data.getPassword().length() > 0)) {
546: try {
547: if (doCreate(admin, data, status)) {
548: successusers += (":" + data
549: .getUsername());
550: successcount++;
551: }
552: } catch (Exception e) {
553: // If things went wrong set status to FAILED
554: String errMsg = intres.getLocalizedMessage(
555: "batch.errorsetstatus", "FAILED");
556: log.error(errMsg, e);
557: failedusers += (":" + data.getUsername());
558: failcount++;
559: if (status == UserDataConstants.STATUS_KEYRECOVERY) {
560: admin
561: .setUserStatus(
562: administrator,
563: data.getUsername(),
564: UserDataConstants.STATUS_KEYRECOVERY);
565: } else {
566: admin
567: .setUserStatus(
568: administrator,
569: data.getUsername(),
570: UserDataConstants.STATUS_FAILED);
571: }
572: }
573: } else {
574: iMsg = intres.getLocalizedMessage(
575: "batch.infonoclearpwd", data
576: .getUsername());
577: log.info(iMsg);
578: }
579: }
580:
581: if (failedusers.length() > 0) {
582: String errMsg = intres.getLocalizedMessage(
583: "batch.errorbatchfailed", new Integer(
584: failcount), new Integer(
585: successcount), failedusers);
586: throw new Exception(errMsg);
587: }
588:
589: iMsg = intres.getLocalizedMessage("batch.success",
590: new Integer(successcount), successusers);
591: log.info(iMsg);
592: }
593: } while ((result.size() > 0) && !stopnow);
594:
595: log.debug("<createAllWithStatus: " + status);
596: } // createAllWithStatus
597:
598: /**
599: * Creates P12-files for one user in the local database.
600: *
601: * @param username username
602: * @throws Exception if the user does not exist or something goes wrong during generation
603: */
604: public void createUser(String username) throws Exception {
605: log.debug(">createUser(" + username + ")");
606:
607: IUserAdminSessionRemote admin = adminhome.create();
608: UserDataVO data = admin.findUser(administrator, username);
609: int status = data.getStatus();
610:
611: if ((data != null) && (data.getPassword() != null)
612: && (data.getPassword().length() > 0)) {
613: if ((status == UserDataConstants.STATUS_NEW)
614: || ((status == UserDataConstants.STATUS_KEYRECOVERY) && usekeyrecovery)) {
615: try {
616: doCreate(admin, data, status);
617: } catch (Exception e) {
618: // If things went wrong set status to FAILED
619: String errMsg = intres.getLocalizedMessage(
620: "batch.errorsetstatus", "FAILED");
621: log.error(errMsg, e);
622: if (status == UserDataConstants.STATUS_KEYRECOVERY) {
623: admin.setUserStatus(administrator, data
624: .getUsername(),
625: UserDataConstants.STATUS_KEYRECOVERY);
626: } else {
627: admin.setUserStatus(administrator, data
628: .getUsername(),
629: UserDataConstants.STATUS_FAILED);
630: }
631: errMsg = intres.getLocalizedMessage(
632: "batch.errorbatchfaileduser", username);
633: throw new Exception(errMsg);
634: }
635: } else {
636: String errMsg = intres.getLocalizedMessage(
637: "batch.errorbatchfaileduser", username);
638: log.error(errMsg);
639: throw new Exception(errMsg);
640: }
641: }
642:
643: log.debug(">createUser(" + username + ")");
644: } // doit
645:
646: /**
647: * Return enviroment variable EJBCA_HOME or an empty string if the variable isn't set.
648: * @return Enviroment variable EJBCA_HOME
649: */
650: private static String getHomeDir() {
651: String ejbcaHomeDir = System.getenv("EJBCA_HOME");
652: if (ejbcaHomeDir == null) {
653: ejbcaHomeDir = "";
654: } else if (!ejbcaHomeDir.endsWith("/")
655: && !ejbcaHomeDir.endsWith("\\")) {
656: ejbcaHomeDir += File.separatorChar;
657: }
658: return ejbcaHomeDir;
659: } // getHomeDir()
660:
661: /**
662: * Main
663: *
664: * @param args command line arguments
665: */
666: public static void main(String[] args) {
667: try {
668: BatchMakeP12 makep12 = new BatchMakeP12();
669: String username = null;
670: String directory = getHomeDir() + "p12";
671: for (int i = 0; i < args.length; i++) {
672: if ("-?".equalsIgnoreCase(args[i])
673: || "--help".equalsIgnoreCase(args[i])) {
674: System.out
675: .println("Usage: batch [username] [-dir directory]");
676: System.out
677: .println(" username: the name of the user to generate the key.");
678: System.out
679: .println(" If omitted, keys will be generated for all users with status NEW or FAILED");
680: System.out
681: .println(" directory: the name of the directory to store the keys to");
682: System.exit(1);
683: } else if ("-dir".equalsIgnoreCase(args[i])) {
684: directory = args[++i];
685: } else {
686: username = args[i];
687: }
688: }
689:
690: // Create subdirectory 'p12' if it does not exist
691: File dir = new File(directory).getCanonicalFile();
692: dir.mkdir();
693: makep12.setMainStoreDir(directory);
694: String iMsg = intres.getLocalizedMessage(
695: "batch.generateindir", dir);
696: log.info(iMsg);
697:
698: if (username != null) {
699: makep12.createUser(username);
700: } else {
701: // Make P12 for all NEW users in local DB
702: makep12.createAllNew();
703:
704: // Make P12 for all FAILED users in local DB
705: makep12.createAllFailed();
706:
707: // Make P12 for all KEYRECOVERABLE users in local DB
708: makep12.createAllKeyRecover();
709: }
710: } catch (Exception e) {
711: e.printStackTrace();
712: System.exit(1);
713: }
714: } // main
715: } // BatchMakeP12
|