From 171aaece4f23709d33d180cf36eb3af5e454b0c9 Mon Sep 17 00:00:00 2001 From: Ade Lee Date: Thu, 8 Dec 2011 21:15:59 -0500 Subject: Revert "Formatting" This reverts commit 32150d3ee32f8ac27118af7c792794b538c78a2f. --- .../java-tools/src/com/netscape/cmstools/AtoB.java | 85 +- .../src/com/netscape/cmstools/AuditVerify.java | 390 +- .../java-tools/src/com/netscape/cmstools/BtoA.java | 63 +- .../src/com/netscape/cmstools/CMCEnroll.java | 288 +- .../src/com/netscape/cmstools/CMCRequest.java | 672 ++- .../src/com/netscape/cmstools/CMCResponse.java | 149 +- .../src/com/netscape/cmstools/CMCRevoke.java | 229 +- .../src/com/netscape/cmstools/CRMFPopClient.java | 858 ++-- .../src/com/netscape/cmstools/DRMTool.java | 5277 ++++++++++++-------- .../src/com/netscape/cmstools/ExtJoiner.java | 27 +- .../src/com/netscape/cmstools/GenExtKeyUsage.java | 24 +- .../com/netscape/cmstools/GenIssuerAltNameExt.java | 44 +- .../netscape/cmstools/GenSubjectAltNameExt.java | 44 +- .../src/com/netscape/cmstools/HttpClient.java | 154 +- .../src/com/netscape/cmstools/OCSPClient.java | 273 +- .../src/com/netscape/cmstools/PKCS10Client.java | 153 +- .../src/com/netscape/cmstools/PKCS12Export.java | 102 +- .../src/com/netscape/cmstools/PasswordCache.java | 371 +- .../src/com/netscape/cmstools/PrettyPrintCert.java | 115 +- .../src/com/netscape/cmstools/PrettyPrintCrl.java | 112 +- .../src/com/netscape/cmstools/TestCRLSigning.java | 53 +- .../src/com/netscape/cmstools/TokenInfo.java | 63 +- 22 files changed, 5314 insertions(+), 4232 deletions(-) (limited to 'pki/base/java-tools/src/com/netscape') diff --git a/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java b/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java index 1e2187840..78c207515 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/AtoB.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; @@ -25,33 +26,33 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; + /** - * The AtoB class is a utility program designed to "translate" an ASCII BASE 64 - * encoded blob into a BINARY BASE 64 encoded blob. It assumes that the name of - * a data file is passed to the program via the command line, and that the - * contents contain a blob encoded in an ASCII BASE 64 format. Note that the - * data file may contain an optional "-----BEGIN" header and/or an optional - * "-----END" trailer. - * + * The AtoB class is a utility program designed to "translate" an ASCII + * BASE 64 encoded blob into a BINARY BASE 64 encoded blob. It assumes + * that the name of a data file is passed to the program via the command line, + * and that the contents contain a blob encoded in an ASCII BASE 64 + * format. Note that the data file may contain an optional "-----BEGIN" header + * and/or an optional "-----END" trailer. + * *

* The program may be invoked as follows: - * *

- * 
+ *
  *      AtoB <input filename> <output filename>
- * 
+ *
  *      NOTE:  <input filename>   must contain an ASCII
  *                                BASE 64 encoded blob
- * 
+ *
  *             <output filename>  contains a BINARY
  *                                BASE 64 encoded blob
  * 
- * + * * @version $Revision$, $Date$ */ public class AtoB { // Define constants - public static final int ARGC = 2; + public static final int ARGC = 2; public static final String HEADER = "-----BEGIN"; public static final String TRAILER = "-----END"; @@ -65,75 +66,81 @@ public class AtoB { // (1) Check that two arguments were submitted to the program if (argv.length != ARGC) { - System.out.println("Usage: AtoB " + " " - + ""); + System.out.println("Usage: AtoB " + + " " + + ""); return; } // (2) Create a DataInputStream() object to the BASE 64 - // encoded blob contained within the file - // specified on the command line + // encoded blob contained within the file + // specified on the command line try { inputBlob = new BufferedReader(new InputStreamReader( - new BufferedInputStream(new FileInputStream(argv[0])))); + new BufferedInputStream( + new FileInputStream( + argv[0])))); } catch (FileNotFoundException e) { - System.out.println("AtoB(): can''t find file " + argv[0] + ":\n" - + e); + System.out.println("AtoB(): can''t find file " + + argv[0] + ":\n" + e); return; } // (3) Read the entire contents of the specified BASE 64 encoded - // blob into a String() object throwing away any - // headers beginning with HEADER and any trailers beginning - // with TRAILER + // blob into a String() object throwing away any + // headers beginning with HEADER and any trailers beginning + // with TRAILER try { while ((asciiBASE64BlobChunk = inputBlob.readLine()) != null) { - if (!(asciiBASE64BlobChunk.startsWith(HEADER)) - && !(asciiBASE64BlobChunk.startsWith(TRAILER))) { + if (!(asciiBASE64BlobChunk.startsWith(HEADER)) && + !(asciiBASE64BlobChunk.startsWith(TRAILER))) { asciiBASE64Blob += asciiBASE64BlobChunk.trim(); } } } catch (IOException e) { - System.out.println("AtoB(): Unexpected BASE64 " - + "encoded error encountered in readLine():\n" + e); + System.out.println("AtoB(): Unexpected BASE64 " + + "encoded error encountered in readLine():\n" + + e); } // (4) Close the DataInputStream() object try { inputBlob.close(); } catch (IOException e) { - System.out.println("AtoB(): Unexpected BASE64 " - + "encoded error encountered in close():\n" + e); + System.out.println("AtoB(): Unexpected BASE64 " + + "encoded error encountered in close():\n" + e); } - + // (5) Decode the ASCII BASE 64 blob enclosed in the - // String() object into a BINARY BASE 64 byte[] object + // String() object into a BINARY BASE 64 byte[] object binaryBASE64Blob = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob); // (6) Finally, print the actual AtoB blob to the - // specified output file + // specified output file try { outputBlob = new FileOutputStream(argv[1]); } catch (IOException e) { - System.out.println("AtoB(): unable to open file " + argv[1] - + " for writing:\n" + e); + System.out.println("AtoB(): unable to open file " + + argv[1] + " for writing:\n" + e); return; } try { outputBlob.write(binaryBASE64Blob); } catch (IOException e) { - System.out.println("AtoB(): I/O error " - + "encountered during write():\n" + e); + System.out.println("AtoB(): I/O error " + + "encountered during write():\n" + + e); } try { outputBlob.close(); } catch (IOException e) { - System.out.println("AtoB(): Unexpected error " - + "encountered while attempting to close() " + argv[1] - + ":\n" + e); + System.out.println("AtoB(): Unexpected error " + + "encountered while attempting to close() " + + argv[1] + ":\n" + e); } } } + diff --git a/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java b/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java index 7679c9f23..aa8ffe9a4 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/AuditVerify.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; @@ -44,8 +45,7 @@ import org.mozilla.jss.crypto.X509Certificate; public class AuditVerify { private static void usage() { - System.out - .println("Usage: AuditVerify -d -n -a [-P ] [-v]"); + System.out.println("Usage: AuditVerify -d -n -a [-P ] [-v]"); System.exit(1); } @@ -69,34 +69,34 @@ public class AuditVerify { } private static void writeSigStatus(int linenum, String sigStartFile, - int sigStartLine, String sigStopFile, int sigStopLine, String mesg) - throws IOException { - output(linenum, mesg + ": signature of " + sigStartFile + ":" - + sigStartLine + " to " + sigStopFile + ":" + sigStopLine); + int sigStartLine, String sigStopFile, int sigStopLine, String mesg) + throws IOException + { + output(linenum, mesg + ": signature of " + sigStartFile + ":" + + sigStartLine + " to " + sigStopFile + ":" + sigStopLine); } private static class PrefixFilter implements FilenameFilter { private String prefix; - public PrefixFilter(String prefix) { this.prefix = prefix; } - public boolean accept(File dir, String name) { // look for cert* in this directory - return (name.indexOf(prefix + "cert") != -1); + return( name.indexOf(prefix + "cert") != -1 ); } } public static boolean validPrefix(String configDir, String prefix) - throws IOException { + throws IOException + { File dir = new File(configDir); - if (!dir.isDirectory()) { + if( ! dir.isDirectory() ) { System.out.println("ERROR: \"" + dir + "\" is not a directory"); usage(); } - String matchingFiles[] = dir.list(new PrefixFilter(prefix)); + String matchingFiles[] = dir.list( new PrefixFilter(prefix) ); // prefix may be valid if at least one file matched the pattern return (matchingFiles.length > 0); @@ -113,224 +113,218 @@ public class AuditVerify { return (keyUsage == null) ? false : keyUsage[0]; } - public static void main(String args[]) { - try { - String dbdir = null; - String logListFile = null; - String signerNick = null; - String prefix = null; - boolean verbose = false; - - for (int i = 0; i < args.length; ++i) { - if (args[i].equals("-d")) { - if (++i >= args.length) - usage(); - dbdir = args[i]; - } else if (args[i].equals("-a")) { - if (++i >= args.length) - usage(); - logListFile = args[i]; - } else if (args[i].equals("-n")) { - if (++i >= args.length) - usage(); - signerNick = args[i]; - } else if (args[i].equals("-P")) { - if (++i >= args.length) - usage(); - prefix = args[i]; - } else if (args[i].equals("-v")) { - verbose = true; - } else { - System.out.println("Unrecognized argument(" + i + "): " - + args[i]); - usage(); - } - } - if (dbdir == null || logListFile == null || signerNick == null) { - System.out.println("Argument omitted"); + public static void main(String args[]) { + try { + + String dbdir = null; + String logListFile = null; + String signerNick = null; + String prefix = null; + boolean verbose = false; + + for(int i = 0; i < args.length; ++i) { + if( args[i].equals("-d") ) { + if( ++i >= args.length ) usage(); + dbdir = args[i]; + } else if( args[i].equals("-a") ) { + if( ++i >= args.length ) usage(); + logListFile = args[i]; + } else if( args[i].equals("-n") ) { + if( ++i >= args.length ) usage(); + signerNick = args[i]; + } else if( args[i].equals("-P") ) { + if( ++i >= args.length ) usage(); + prefix = args[i]; + } else if( args[i].equals("-v") ) { + verbose = true; + } else { + System.out.println("Unrecognized argument(" + i + "): " + + args[i]); usage(); } + } + if( dbdir == null || logListFile == null || signerNick == null) { + System.out.println("Argument omitted"); + usage(); + } - // get list of log files - Vector logFiles = new Vector(); - BufferedReader r = new BufferedReader(new FileReader(logListFile)); - String listLine; - while ((listLine = r.readLine()) != null) { - StringTokenizer tok = new StringTokenizer(listLine, ","); - while (tok.hasMoreElements()) { - logFiles.addElement(((String) tok.nextElement()).trim()); - } - } - if (logFiles.size() == 0) { - System.out.println("Error: no log files listed in " - + logListFile); - System.exit(1); + // get list of log files + Vector logFiles = new Vector(); + BufferedReader r = new BufferedReader(new FileReader(logListFile)); + String listLine; + while( (listLine = r.readLine()) != null ) { + StringTokenizer tok = new StringTokenizer(listLine, ","); + while( tok.hasMoreElements() ) { + logFiles.addElement( ((String)tok.nextElement()).trim()); } + } + if( logFiles.size() == 0 ) { + System.out.println("Error: no log files listed in " + logListFile); + System.exit(1); + } - // initialize crypto stuff - if (prefix == null) { - if (!validPrefix(dbdir, "")) { - System.out.println("ERROR: \"" + dbdir - + "\" does not contain any security databases"); - usage(); - } - CryptoManager.initialize(dbdir); - } else { - if (!validPrefix(dbdir, prefix)) { - System.out.println("ERROR: \"" + prefix - + "\" is not a valid prefix"); - usage(); - } - CryptoManager - .initialize(new CryptoManager.InitializationValues( - dbdir, prefix, prefix, "secmod.db")); + // initialize crypto stuff + if( prefix == null ) { + if( ! validPrefix(dbdir, "")) { + System.out.println("ERROR: \"" + dbdir + + "\" does not contain any security databases"); + usage(); } - CryptoManager cm = CryptoManager.getInstance(); - X509Certificate signerCert = cm.findCertByNickname(signerNick); - - X509CertImpl cert_i = null; - if (signerCert != null) { - byte[] signerCert_b = signerCert.getEncoded(); - cert_i = new X509CertImpl(signerCert_b); - } else { - System.out.println("ERROR: signing certificate not found"); - System.exit(1); + CryptoManager.initialize(dbdir); + } else { + if( ! validPrefix(dbdir, prefix) ) { + System.out.println("ERROR: \"" + prefix + + "\" is not a valid prefix"); + usage(); } + CryptoManager.initialize( + new CryptoManager.InitializationValues(dbdir, prefix, prefix, + "secmod.db") + ); + } + CryptoManager cm = CryptoManager.getInstance(); + X509Certificate signerCert = cm.findCertByNickname(signerNick); + + X509CertImpl cert_i = null; + if (signerCert != null) { + byte[] signerCert_b = signerCert.getEncoded(); + cert_i = new X509CertImpl(signerCert_b); + } else { + System.out.println("ERROR: signing certificate not found"); + System.exit(1); + } - // verify signer's certificate - // not checking validity because we want to allow verifying old logs - // - if (!isSigningCert(cert_i)) { - System.out - .println("info: signing certificate is not a signing certificate"); - System.exit(1); - } + // verify signer's certificate + // not checking validity because we want to allow verifying old logs + // + if (!isSigningCert(cert_i)) { + System.out.println("info: signing certificate is not a signing certificate"); + System.exit(1); + } - PublicKey pubk = signerCert.getPublicKey(); - String sigAlgorithm = null; - if (pubk instanceof RSAPublicKey) { - sigAlgorithm = "SHA-256/RSA"; - } else if (pubk instanceof DSAPublicKey) { - sigAlgorithm = "SHA-256/DSA"; - } else { - System.out.println("Error: unknown key type: " - + pubk.getAlgorithm()); - System.exit(1); - } - Signature sig = Signature - .getInstance(sigAlgorithm, CRYPTO_PROVIDER); - sig.initVerify(pubk); + PublicKey pubk = signerCert.getPublicKey(); + String sigAlgorithm=null; + if( pubk instanceof RSAPublicKey ) { + sigAlgorithm = "SHA-256/RSA"; + } else if( pubk instanceof DSAPublicKey ) { + sigAlgorithm = "SHA-256/DSA"; + } else { + System.out.println("Error: unknown key type: " + + pubk.getAlgorithm()); + System.exit(1); + } + Signature sig = Signature.getInstance(sigAlgorithm, CRYPTO_PROVIDER); + sig.initVerify(pubk); - int goodSigCount = 0; - int badSigCount = 0; + int goodSigCount = 0; + int badSigCount = 0; - int lastFileWritten = -1; + int lastFileWritten = -1; - int sigStartLine = 1; - int sigStopLine = 1; - String sigStartFile = (String) logFiles.elementAt(0); - String sigStopFile = null; - int signedLines = 1; + int sigStartLine = 1; + int sigStopLine = 1; + String sigStartFile = (String) logFiles.elementAt(0); + String sigStopFile = null; + int signedLines = 1; - boolean lastLineWasSig = false; + boolean lastLineWasSig = false; - for (int curfile = 0; curfile < logFiles.size(); ++curfile) { - String curfileName = (String) logFiles.elementAt(curfile); - BufferedReader br = new BufferedReader(new FileReader( - curfileName)); + for( int curfile = 0; curfile < logFiles.size(); ++curfile) { + String curfileName = (String) logFiles.elementAt(curfile); + BufferedReader br = new BufferedReader(new FileReader(curfileName)); - if (verbose) { - writeFile(curfileName); - lastFileWritten = curfile; - } + if( verbose ) { + writeFile(curfileName); + lastFileWritten = curfile; + } - String curLine; - int linenum = 0; - while ((curLine = br.readLine()) != null) { - ++linenum; - if (curLine.indexOf("AUDIT_LOG_SIGNING") != -1) { - if (curfile == 0 && linenum == 1) { - // Ignore the first signature of the first file, - // since it signs data we don't have access to. - if (verbose) { - output(linenum, - "Ignoring first signature of log series"); - } + String curLine; + int linenum = 0; + while( (curLine = br.readLine()) != null ) { + ++linenum; + if( curLine.indexOf("AUDIT_LOG_SIGNING") != -1 ) { + if( curfile == 0 && linenum == 1 ) { + // Ignore the first signature of the first file, + // since it signs data we don't have access to. + if( verbose ) { + output(linenum, + "Ignoring first signature of log series"); + } + } else { + int sigStart = curLine.indexOf("sig: ") + 5; + if( sigStart < 5 ) { + output(linenum, "INVALID SIGNATURE"); + ++badSigCount; } else { - int sigStart = curLine.indexOf("sig: ") + 5; - if (sigStart < 5) { - output(linenum, "INVALID SIGNATURE"); - ++badSigCount; - } else { - byte[] logSig = base64decode(curLine - .substring(sigStart)); - - // verify the signature - if (sig.verify(logSig)) { - // signature verifies correctly - if (verbose) { - writeSigStatus(linenum, sigStartFile, - sigStartLine, sigStopFile, - sigStopLine, - "verification succeeded"); - } - ++goodSigCount; - } else { - if (lastFileWritten < curfile) { - writeFile(curfileName); - lastFileWritten = curfile; - } + byte[] logSig = + base64decode(curLine.substring(sigStart)); + + // verify the signature + if( sig.verify(logSig) ) { + // signature verifies correctly + if( verbose ) { writeSigStatus(linenum, sigStartFile, - sigStartLine, sigStopFile, - sigStopLine, "VERIFICATION FAILED"); - ++badSigCount; + sigStartLine, sigStopFile, sigStopLine, + "verification succeeded"); } + ++goodSigCount; + } else { + if( lastFileWritten < curfile ) { + writeFile(curfileName); + lastFileWritten = curfile; + } + writeSigStatus(linenum, sigStartFile, + sigStartLine, sigStopFile, sigStopLine, + "VERIFICATION FAILED"); + ++badSigCount; } - sig.initVerify(pubk); - signedLines = 0; - sigStartLine = linenum; - sigStartFile = curfileName; } + sig.initVerify(pubk); + signedLines = 0; + sigStartLine = linenum; + sigStartFile = curfileName; } - - byte[] lineBytes = curLine.getBytes("UTF-8"); - sig.update(lineBytes); - sig.update(LINE_SEP_BYTE); - ++signedLines; - sigStopLine = linenum; - sigStopFile = curfileName; } + byte[] lineBytes = curLine.getBytes("UTF-8"); + sig.update(lineBytes); + sig.update(LINE_SEP_BYTE); + ++signedLines; + sigStopLine = linenum; + sigStopFile = curfileName; } - // Make sure there were no unsigned log entries at the end. - // The first signed line is the previous signature, but anything - // more than that is data. - if (signedLines > 1) { - System.out.println("ERROR: log entries after " + sigStartFile - + ":" + sigStartLine + " are UNSIGNED"); - badSigCount++; - } + } - System.out.println("\nVerification process complete."); - System.out.println("Valid signatures: " + goodSigCount); - System.out.println("Invalid signatures: " + badSigCount); + // Make sure there were no unsigned log entries at the end. + // The first signed line is the previous signature, but anything + // more than that is data. + if( signedLines > 1 ) { + System.out.println( + "ERROR: log entries after " + sigStartFile + + ":" + sigStartLine + " are UNSIGNED"); + badSigCount++; + } - if (badSigCount > 0) { - System.exit(2); - } else { - System.exit(0); - } + System.out.println("\nVerification process complete."); + System.out.println("Valid signatures: " + goodSigCount); + System.out.println("Invalid signatures: " + badSigCount); - } catch (FileNotFoundException fnfe) { - System.out.println(fnfe); - } catch (ObjectNotFoundException onfe) { - System.out.println("ERROR: certificate not found"); - } catch (Exception e) { - e.printStackTrace(); + if( badSigCount > 0 ) { + System.exit(2); + } else { + System.exit(0); } + } catch(FileNotFoundException fnfe) { + System.out.println(fnfe); + } catch(ObjectNotFoundException onfe) { + System.out.println("ERROR: certificate not found"); + } catch(Exception e) { + e.printStackTrace(); + } + System.out.println("Verification process FAILED."); System.exit(1); } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java b/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java index 3d8df6930..2bc96a2fd 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/BtoA.java @@ -17,67 +17,70 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; + /** - * The BtoA class is a utility program designed to "translate" a BINARY BASE 64 - * encoded blob into an ASCII BASE 64 encoded blob. It assumes that the name of - * a data file is passed to the program via the command line, and that the - * contents contain a blob encoded in a BINARY BASE 64 format. - * + * The BtoA class is a utility program designed to "translate" a BINARY + * BASE 64 encoded blob into an ASCII BASE 64 encoded blob. It assumes + * that the name of a data file is passed to the program via the command line, + * and that the contents contain a blob encoded in a BINARY BASE 64 + * format. + * *

* The program may be invoked as follows: - * *

- * 
+ *
  *      BtoA <input filename> <output filename>
- * 
+ *
  *      NOTE:  <input filename>   must contain a BINARY
  *                                BASE 64 encoded blob
- * 
+ *
  *             <output filename>  contains an ASCII
  *                                BASE 64 encoded blob
  * 
- * + * * @version $Revision$, $Date$ */ public class BtoA { // Define constants - public static final int ARGC = 2; + public static final int ARGC = 2; public static void main(String argv[]) { - FileInputStream inputBlob = null; + FileInputStream inputBlob = null; FileOutputStream outputBlob = null; // (1) Check that two arguments were submitted to the program if (argv.length != ARGC) { - System.out.println("Usage: BtoA " + " " - + ""); + System.out.println("Usage: BtoA " + + " " + + ""); return; } // (2) Create a DataInputStream() object to the BASE 64 - // encoded blob contained within the file - // specified on the command line + // encoded blob contained within the file + // specified on the command line try { inputBlob = new FileInputStream(argv[0]); } catch (FileNotFoundException e) { - System.out.println("BtoA(): can''t find file " + argv[0] + ":\n" - + e); + System.out.println("BtoA(): can''t find file " + + argv[0] + ":\n" + e); return; } // (3) Create a FileOutputStream() object to the BASE 64 - // specified output file + // specified output file try { outputBlob = new FileOutputStream(argv[1]); } catch (IOException e) { - System.out.println("BtoA(): unable to open file " + argv[1] - + " for writing:\n" + e); + System.out.println("BtoA(): unable to open file " + + argv[1] + " for writing:\n" + e); return; } @@ -89,26 +92,28 @@ public class BtoA { String out = com.netscape.osutil.OSUtil.BtoA(data); outputBlob.write(out.getBytes()); } catch (IOException e) { - System.out.println("BtoA(): Unexpected BASE64 " - + "encoded error encountered:\n" + e); + System.out.println("BtoA(): Unexpected BASE64 " + + "encoded error encountered:\n" + + e); } // (5) Close the DataInputStream() object try { inputBlob.close(); } catch (IOException e) { - System.out.println("BtoA(): Unexpected input error " - + "encountered while attempting to close() " + argv[0] - + ":\n" + e); + System.out.println("BtoA(): Unexpected input error " + + "encountered while attempting to close() " + + argv[0] + ":\n" + e); } // (6) Close the FileOutputStream() object try { outputBlob.close(); } catch (IOException e) { - System.out.println("BtoA(): Unexpected output error " - + "encountered while attempting to close() " + argv[1] - + ":\n" + e); + System.out.println("BtoA(): Unexpected output error " + + "encountered while attempting to close() " + + argv[1] + ":\n" + e); } } } + diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java b/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java index a870fbabc..368ef8278 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/CMCEnroll.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -66,30 +67,32 @@ import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier; import org.mozilla.jss.pkix.primitive.Name; import org.mozilla.jss.util.Password; + + /** * Tool for signing PKCS #10 , return CMC enrollment request * *

- * * @version $Revision$, $Date$ + */ public class CMCEnroll { public static final String PR_REQUEST_CMC = "CMC"; public static final String PR_REQUEST_PKCS10 = "PKCS10"; - public static final int ARGC = 4; + public static final int ARGC = 4; private static final String CERTDB = "cert8.db"; private static final String KEYDB = "key3.db"; public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----"; public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----"; - - void cleanArgs(String[] s) { - + + void cleanArgs(String[] s) { + } public static X509Certificate getCertificate(String tokenname, - String nickname) throws Exception { + String nickname) throws Exception { CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = null; @@ -112,42 +115,39 @@ public class CMCEnroll { } } - public static java.security.PrivateKey getPrivateKey(String tokenname, - String nickname) throws Exception { + public static java.security.PrivateKey getPrivateKey(String tokenname, String nickname) + throws Exception { X509Certificate cert = getCertificate(tokenname, nickname); return CryptoManager.getInstance().findPrivKeyByCert(cert); } - /** - * getCMCBlob create and return the enrollent request. - *

- * - * @param signerCert the certificate of the authorized signer of the CMC - * revocation request. - * @param manager the crypto manger. - * @param nValue the nickname of the certificate inside the token. - * @param rValue request PKCS#10 file name. - * @return the CMC revocation request encoded in base64 - */ - static String getCMCBlob(X509Certificate signerCert, CryptoManager manager, - String nValue, String rValue) { + /** + * getCMCBlob create and return the enrollent request. + *

+ * @param signerCert the certificate of the authorized signer of the CMC revocation request. + * @param manager the crypto manger. + * @param nValue the nickname of the certificate inside the token. + * @param rValue request PKCS#10 file name. + * @return the CMC revocation request encoded in base64 + */ + static String getCMCBlob(X509Certificate signerCert,CryptoManager manager, String nValue, String rValue) { + String asciiBASE64Blob = rValue; // input pkcs10 blob String tokenname = "internal"; try { - + java.security.PrivateKey privKey = null; PKCS10 pkcs = null; SignerIdentifier si = null; ContentInfo fullEnrollmentReq = null; try { - byte[] decodedBytes = com.netscape.osutil.OSUtil - .AtoB(asciiBASE64Blob); - + byte[] decodedBytes = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob); + pkcs = new PKCS10(decodedBytes); } catch (IOException e) { throw new IOException("Internal Error - " + e.toString()); @@ -156,7 +156,7 @@ public class CMCEnroll { } catch (NoSuchAlgorithmException e) { throw new IOException("Internal Error - " + e.toString()); } - + String hasSki = "true"; BigInteger serialno = signerCert.getSerialNumber(); @@ -164,37 +164,35 @@ public class CMCEnroll { X509CertImpl impl = new X509CertImpl(certB); X500Name issuerName = (X500Name) impl.getIssuerDN(); byte[] issuerByte = issuerName.getEncoded(); - ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte); - + ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte); + Name issuer = (Name) Name.getTemplate().decode(istream); - IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, - new INTEGER(serialno.toString())); + IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, new INTEGER(serialno.toString())); - si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, - ias, null); + si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null); privKey = getPrivateKey(tokenname, nValue); - + // create CMC req // transfer pkcs10 to jss class int bpid = 1; - ByteArrayInputStream crInputStream = new ByteArrayInputStream( - pkcs.toByteArray()); - CertificationRequest cr = (CertificationRequest) CertificationRequest - .getTemplate().decode(crInputStream); - - TaggedCertificationRequest tcr = new TaggedCertificationRequest( - new INTEGER(bpid++), cr); - TaggedRequest trq = new TaggedRequest(TaggedRequest.PKCS10, tcr, + ByteArrayInputStream crInputStream = new ByteArrayInputStream(pkcs.toByteArray()); + CertificationRequest cr = (CertificationRequest) CertificationRequest.getTemplate().decode(crInputStream); + + TaggedCertificationRequest tcr = new + TaggedCertificationRequest(new + INTEGER(bpid++), cr); + TaggedRequest trq = new + TaggedRequest(TaggedRequest.PKCS10, tcr, null); - + SEQUENCE reqSequence = new SEQUENCE(); reqSequence.addElement(trq); - + // Add some control sequence // Verisign has transactionID,senderNonce SEQUENCE controlSeq = new SEQUENCE(); - + Date date = new Date(); String salt = "lala123" + date.toString(); byte[] dig; @@ -208,44 +206,43 @@ public class CMCEnroll { } String sn = com.netscape.osutil.OSUtil.BtoA(dig); - - TaggedAttribute senderNonce = new TaggedAttribute(new INTEGER( - bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce, + + TaggedAttribute senderNonce = new TaggedAttribute(new + INTEGER(bpid++), + OBJECT_IDENTIFIER.id_cmc_senderNonce, new OCTET_STRING(sn.getBytes())); controlSeq.addElement(senderNonce); - + // Verisign recommend transactionId be MD5 hash of publicKey byte[] transId; try { MessageDigest MD5Digest = MessageDigest.getInstance("MD5"); - transId = MD5Digest.digest(pkcs.getSubjectPublicKeyInfo() - .getKey()); + transId = MD5Digest.digest(pkcs.getSubjectPublicKeyInfo().getKey()); } catch (Exception ex) { transId = salt.getBytes(); } - - TaggedAttribute transactionId = new TaggedAttribute(new INTEGER( - bpid++), OBJECT_IDENTIFIER.id_cmc_transactionId, + + TaggedAttribute transactionId = new TaggedAttribute(new + INTEGER(bpid++), + OBJECT_IDENTIFIER.id_cmc_transactionId, new INTEGER(1, transId)); controlSeq.addElement(transactionId); - - PKIData pkidata = new PKIData(controlSeq, reqSequence, - new SEQUENCE(), new SEQUENCE()); - - EncapsulatedContentInfo ci = new EncapsulatedContentInfo( - OBJECT_IDENTIFIER.id_cct_PKIData, pkidata); + + PKIData pkidata = new PKIData(controlSeq, reqSequence, new SEQUENCE(), new SEQUENCE()); + + EncapsulatedContentInfo ci = new + EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData, + pkidata); // SHA1 is the default digest Alg for now. DigestAlgorithm digestAlg = null; SignatureAlgorithm signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest; - org.mozilla.jss.crypto.PrivateKey.Type signingKeyType = ((org.mozilla.jss.crypto.PrivateKey) privKey) - .getType(); + org.mozilla.jss.crypto.PrivateKey.Type signingKeyType = ((org.mozilla.jss.crypto.PrivateKey) privKey).getType(); - if (signingKeyType - .equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA)) + if (signingKeyType.equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA)) signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest; MessageDigest SHADigest = null; byte[] digest = null; @@ -253,31 +250,29 @@ public class CMCEnroll { try { SHADigest = MessageDigest.getInstance("SHA1"); digestAlg = DigestAlgorithm.SHA1; - + ByteArrayOutputStream ostream = new ByteArrayOutputStream(); pkidata.encode((OutputStream) ostream); digest = SHADigest.digest(ostream.toByteArray()); } catch (NoSuchAlgorithmException e) { } - SignerInfo signInfo = new SignerInfo(si, null, null, - OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg, + SignerInfo signInfo = new + SignerInfo(si, null, null, OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg, (org.mozilla.jss.crypto.PrivateKey) privKey); SET signInfos = new SET(); signInfos.addElement(signInfo); - + SET digestAlgs = new SET(); if (digestAlg != null) { - AlgorithmIdentifier ai = new AlgorithmIdentifier( - digestAlg.toOID(), null); + AlgorithmIdentifier ai = new AlgorithmIdentifier(digestAlg.toOID(), null); digestAlgs.addElement(ai); } - - org.mozilla.jss.crypto.X509Certificate[] agentChain = manager - .buildCertificateChain(signerCert); + + org.mozilla.jss.crypto.X509Certificate[] agentChain = manager.buildCertificateChain(signerCert); SET certs = new SET(); for (int i = 0; i < agentChain.length; i++) { @@ -285,20 +280,20 @@ public class CMCEnroll { certs.addElement(cert); } - SignedData req = new SignedData(digestAlgs, ci, certs, null, - signInfos); + SignedData req = new SignedData(digestAlgs, ci, certs, null, signInfos); - fullEnrollmentReq = new ContentInfo(req); + fullEnrollmentReq = new + ContentInfo(req); ByteArrayOutputStream bs = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bs); - + // format is PR_REQUEST_CMC - ByteArrayOutputStream os = new ByteArrayOutputStream(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); - fullEnrollmentReq.encode(os); - ps.print(com.netscape.osutil.OSUtil.BtoA(os.toByteArray())); - // fullEnrollmentReq.print(ps); // no header/trailer + fullEnrollmentReq.encode(os); + ps.print(com.netscape.osutil.OSUtil.BtoA(os.toByteArray())); + //fullEnrollmentReq.print(ps); // no header/trailer asciiBASE64Blob = bs.toString(); } catch (Exception e) { e.printStackTrace(); @@ -308,68 +303,74 @@ public class CMCEnroll { } /** Creates a new instance of CMCEnroll */ - public static void main(String[] s) { - + public static void main(String[]s) { + String dValue = null, nValue = null, rValue = null, pValue = null; FileOutputStream outputBlob = null; - + // default path is "." String mPath = "."; // default prefix is "" String mPrefix = ""; - + boolean bWrongParam = false; // (1) Check that two arguments were submitted to the program if (s.length != (ARGC * 2)) { System.out.println("Wrong number of parameters:" + s.length); - System.out.println("Usage: CMCEnroll " - + "-d

" + "-n " - + "-r " + "-p "); + System.out.println("Usage: CMCEnroll " + + "-d " + + "-n " + + "-r " + + "-p " + ); bWrongParam = true; - } else { + }else { int length; int i; - + length = s.length; for (i = 0; i < length; i++) { if (s[i].equals("-d")) { dValue = s[i + 1]; - } else if (s[i].equals("-n")) { + } else if (s[i].equals("-n")) { nValue = s[i + 1]; - } else if (s[i].equals("-r")) { + } else if (s[i].equals("-r")) { rValue = s[i + 1]; - } else if (s[i].equals("-p")) { + } else if (s[i].equals("-p")) { pValue = s[i + 1]; } if (s[i].equals("")) bWrongParam = true; - + } - - if (dValue == null || nValue == null || rValue == null - || pValue == null) + + if (dValue == null || nValue == null || rValue == null || pValue == null ) bWrongParam = true; - else if (dValue.length() == 0 || nValue.length() == 0 - || rValue.length() == 0 || pValue.length() == 0) + else if (dValue.length() == 0 || nValue.length() == 0 || rValue.length() == 0 || + pValue.length() == 0 ) bWrongParam = true; if (bWrongParam == true) { - System.out.println("Usage: CMCEnroll " - + "-d " + "-n " - + "-r " + "-p "); + System.out.println("Usage: CMCEnroll " + + "-d " + + "-n " + + "-r " + + "-p " + ); System.exit(0); - } - + } + try { // initialize CryptoManager mPath = dValue; System.out.println("cert/key prefix = " + mPrefix); System.out.println("path = " + mPath); - CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues( - mPath, mPrefix, mPrefix, "secmod.db"); + CryptoManager.InitializationValues vals = + new CryptoManager.InitializationValues(mPath, mPrefix, + mPrefix, "secmod.db"); CryptoManager.initialize(vals); - + CryptoManager cm = CryptoManager.getInstance(); CryptoToken token = cm.getInternalKeyStorageToken(); Password pass = new Password(pValue.toCharArray()); @@ -378,91 +379,92 @@ public class CMCEnroll { CryptoStore store = token.getCryptoStore(); X509Certificate[] list = store.getCertificates(); X509Certificate signerCert = null; - + signerCert = cm.findCertByNickname(nValue); - - BufferedReader inputBlob = null; + + BufferedReader inputBlob = null; try { - inputBlob = new BufferedReader( - new InputStreamReader(new BufferedInputStream( - new FileInputStream(rValue)))); + inputBlob = new BufferedReader(new InputStreamReader( + new BufferedInputStream( + new FileInputStream( + rValue)))); } catch (FileNotFoundException e) { - System.out.println("CMCEnroll: can''t find file " + rValue - + ":\n" + e); + System.out.println("CMCEnroll: can''t find file " + + rValue + ":\n" + e); return; } catch (Exception e) { e.printStackTrace(); System.exit(1); } // (3) Read the entire contents of the specified BASE 64 encoded - // blob into a String() object throwing away any - // headers beginning with HEADER and any trailers beginning - // with TRAILER + // blob into a String() object throwing away any + // headers beginning with HEADER and any trailers beginning + // with TRAILER String asciiBASE64BlobChunk = new String(); String asciiBASE64Blob = new String(); try { while ((asciiBASE64BlobChunk = inputBlob.readLine()) != null) { - if (!(asciiBASE64BlobChunk.startsWith(HEADER)) - && !(asciiBASE64BlobChunk.startsWith(TRAILER))) { + if (!(asciiBASE64BlobChunk.startsWith(HEADER)) && + !(asciiBASE64BlobChunk.startsWith(TRAILER))) { asciiBASE64Blob += asciiBASE64BlobChunk.trim(); } } } catch (IOException e) { - System.out.println("CMCEnroll: Unexpected BASE64 " - + "encoded error encountered in readLine():\n" + e); + System.out.println("CMCEnroll: Unexpected BASE64 " + + "encoded error encountered in readLine():\n" + + e); } // (4) Close the DataInputStream() object try { inputBlob.close(); } catch (IOException e) { - System.out.println("CMCEnroll(): Unexpected BASE64 " - + "encoded error encountered in close():\n" + e); + System.out.println("CMCEnroll(): Unexpected BASE64 " + + "encoded error encountered in close():\n" + e); } - - asciiBASE64Blob = getCMCBlob(signerCert, cm, nValue, - asciiBASE64Blob); + + asciiBASE64Blob = getCMCBlob(signerCert,cm, nValue, asciiBASE64Blob ); // (5) Decode the ASCII BASE 64 blob enclosed in the - // String() object into a BINARY BASE 64 byte[] object + // String() object into a BINARY BASE 64 byte[] object byte binaryBASE64Blob[] = null; - binaryBASE64Blob = com.netscape.osutil.OSUtil - .AtoB(asciiBASE64Blob); - + binaryBASE64Blob = com.netscape.osutil.OSUtil.AtoB(asciiBASE64Blob); + // (6) Finally, print the actual CMCEnroll blob to the - // specified output file + // specified output file try { outputBlob = new FileOutputStream(rValue + ".out"); } catch (IOException e) { - System.out.println("CMCEnroll: unable to open file " - + rValue + ".out" + " for writing:\n" + e); + System.out.println("CMCEnroll: unable to open file " + + rValue + ".out" + " for writing:\n" + e); return; } - + System.out.println(HEADER); System.out.println(asciiBASE64Blob + TRAILER); try { asciiBASE64Blob = HEADER + "\n" + asciiBASE64Blob + TRAILER; outputBlob.write(asciiBASE64Blob.getBytes()); } catch (IOException e) { - System.out.println("CMCEnroll: I/O error " - + "encountered during write():\n" + e); + System.out.println("CMCEnroll: I/O error " + + "encountered during write():\n" + + e); } - + try { outputBlob.close(); } catch (IOException e) { - System.out.println("CMCEnroll: Unexpected error " - + "encountered while attempting to close() " + "\n" - + e); + System.out.println("CMCEnroll: Unexpected error " + + "encountered while attempting to close() " + + "\n" + e); } - - } catch (Exception e) { + + }catch (Exception e) { e.printStackTrace(); System.exit(1); } - + return; } } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java b/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java index 859bafd4e..e7a23a85a 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/CMCRequest.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -84,31 +85,31 @@ import org.mozilla.jss.util.Password; import com.netscape.cmsutil.util.HMACDigest; + /** * Tool for creating CMC full request * *

- * * @version $Revision$, $Date$ - * + * */ public class CMCRequest { public static final String PR_REQUEST_CMC = "CMC"; public static final String PR_REQUEST_CRMF = "CRMF"; - public static final int ARGC = 1; + public static final int ARGC = 1; private static final String CERTDB = "cert8.db"; private static final String KEYDB = "key3.db"; public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----"; public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----"; - - void cleanArgs(String[] s) { - + + void cleanArgs(String[] s) { + } public static X509Certificate getCertificate(String tokenname, - String nickname) throws Exception { + String nickname) throws Exception { CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = null; @@ -131,31 +132,29 @@ public class CMCRequest { } } - public static java.security.PrivateKey getPrivateKey(String tokenname, - String nickname) throws Exception { + public static java.security.PrivateKey getPrivateKey(String tokenname, String nickname) + throws Exception { X509Certificate cert = getCertificate(tokenname, nickname); return CryptoManager.getInstance().findPrivKeyByCert(cert); } + /** * getCMCBlob create and return the enrollent request. *

- * - * @param signerCert the certificate of the authorized signer of the CMC - * revocation request. + * @param signerCert the certificate of the authorized signer of the CMC revocation request. * @param nickname the nickname of the certificate inside the token. * @param rValue CRMF/PKCS10 request. - * @param format either crmf or pkcs10 + * @param format either crmf or pkcs10 * @return the CMC enrollment request encoded in base64 */ - static ContentInfo getCMCBlob(X509Certificate signerCert, String nickname, - String[] rValue, String format, CryptoManager manager, - String transactionMgtEnable, String transactionMgtId, - String identityProofEnable, String identityProofSharedSecret, - SEQUENCE controlSeq, SEQUENCE otherMsgSeq, int bpid) { - + static ContentInfo getCMCBlob(X509Certificate signerCert, String nickname, + String[] rValue, String format, CryptoManager manager, String transactionMgtEnable, + String transactionMgtId, String identityProofEnable, String identityProofSharedSecret, + SEQUENCE controlSeq, SEQUENCE otherMsgSeq, int bpid) { + String tokenname = "internal"; ContentInfo fullEnrollmentReq = null; @@ -168,61 +167,59 @@ public class CMCRequest { X509CertImpl impl = new X509CertImpl(certB); X500Name issuerName = (X500Name) impl.getIssuerDN(); byte[] issuerByte = issuerName.getEncoded(); - ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte); - + ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte); + Name issuer = (Name) Name.getTemplate().decode(istream); - IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, - new INTEGER(serialno.toString())); + IssuerAndSerialNumber ias = new IssuerAndSerialNumber( + issuer, new INTEGER(serialno.toString())); - si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, - ias, null); + si = new SignerIdentifier( + SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null); privKey = getPrivateKey(tokenname, nickname); TaggedRequest trq = null; PKCS10 pkcs = null; CertReqMsg certReqMsg = null; - + // create CMC req SEQUENCE reqSequence = new SEQUENCE(); try { - for (int k = 0; k < rValue.length; k++) { - String asciiBASE64Blob = rValue[k]; - byte[] decodedBytes = com.netscape.osutil.OSUtil - .AtoB(asciiBASE64Blob); - + for (int k=0; k"); System.out.println("For example, CMCRequest CMCRequest.cfg"); System.out.println(""); - System.out - .println("The configuration file should look like as follows:"); + System.out.println("The configuration file should look like as follows:"); System.out.println(""); - System.out - .println("#numRequests: Total number of PKCS10 requests or CRMF requests."); + System.out.println("#numRequests: Total number of PKCS10 requests or CRMF requests."); System.out.println("numRequests=1"); System.out.println(""); - System.out - .println("#input: full path for the PKCS10 request or CRMF request,"); + System.out.println("#input: full path for the PKCS10 request or CRMF request,"); System.out.println("#the content must be in Base-64 encoded format"); - System.out - .println("#Multiple files are supported. They must be separated by space."); + System.out.println("#Multiple files are supported. They must be separated by space."); System.out.println("input=crmf1"); System.out.println(""); - System.out - .println("#output: full path for the CMC request in binary format"); + System.out.println("#output: full path for the CMC request in binary format"); System.out.println("output=/u/doc/cmcReq"); System.out.println(""); - System.out - .println("#nickname: nickname for agent certificate which will be used"); + System.out.println("#nickname: nickname for agent certificate which will be used"); System.out.println("#to sign the CMC full request."); System.out.println("nickname=CMS Agent Certificate"); System.out.println(""); - System.out - .println("#dbdir: directory for cert8.db, key3.db and secmod.db"); + System.out.println("#dbdir: directory for cert8.db, key3.db and secmod.db"); System.out.println("dbdir=/u/smith/.netscape"); System.out.println(""); - System.out - .println("#password: password for cert8.db which stores the agent"); + System.out.println("#password: password for cert8.db which stores the agent"); System.out.println("#certificate"); System.out.println("password=pass"); System.out.println(""); System.out.println("#format: request format, either pkcs10 or crmf"); System.out.println("format=crmf"); System.out.println(""); - System.out - .println("#confirmCertAcceptance.enable: if true, then the request will"); + System.out.println("#confirmCertAcceptance.enable: if true, then the request will"); System.out.println("#contain this control. Otherwise, false."); System.out.println("confirmCertAcceptance.enable=true"); System.out.println(""); - System.out - .println("#confirmCertAcceptance.serial: The serial number for"); + System.out.println("#confirmCertAcceptance.serial: The serial number for"); System.out.println("#confirmCertAcceptance control"); System.out.println("confirmCertAcceptance.serial=3"); System.out.println(""); - System.out - .println("#confirmCertAcceptance.issuer: The issuer name for"); + System.out.println("#confirmCertAcceptance.issuer: The issuer name for"); System.out.println("#confirmCertAcceptance control"); - System.out - .println("confirmCertAcceptance.issuer=cn=Certificate Manager,c=us"); + System.out.println("confirmCertAcceptance.issuer=cn=Certificate Manager,c=us"); System.out.println(""); - System.out - .println("#getCert.enable: if true, then the request will contain this"); + System.out.println("#getCert.enable: if true, then the request will contain this"); System.out.println("#control. Otherwise, false."); System.out.println("getCert.enable=true"); System.out.println(""); - System.out - .println("#getCert.serial: The serial number for getCert control"); + System.out.println("#getCert.serial: The serial number for getCert control"); System.out.println("getCert.serial=3"); System.out.println(""); - System.out - .println("#getCert.issuer: The issuer name for getCert control"); + System.out.println("#getCert.issuer: The issuer name for getCert control"); System.out.println("getCert.issuer=cn=Certificate Manager,c=us"); System.out.println(""); - System.out - .println("#dataReturn.enable: if true, then the request will contain"); + System.out.println("#dataReturn.enable: if true, then the request will contain"); System.out.println("#this control. Otherwise, false."); System.out.println("dataReturn.enable=true"); System.out.println(""); System.out.println("#dataReturn.data: data contained in the control."); System.out.println("dataReturn.data=test"); System.out.println(""); - System.out - .println("#transactionMgt.enable: if true, then the request will contain"); + System.out.println("#transactionMgt.enable: if true, then the request will contain"); System.out.println("#this control. Otherwise, false."); System.out.println("transactionMgt.enable=true"); System.out.println(""); - System.out - .println("#transactionMgt.id: transaction identifier. Verisign recommend"); + System.out.println("#transactionMgt.id: transaction identifier. Verisign recommend"); System.out.println("#transactionId to be MD5 hash of publicKey."); System.out.println("transactionMgt.id="); System.out.println(""); - System.out - .println("#senderNonce.enable: if true, then the request will contain this"); + System.out.println("#senderNonce.enable: if true, then the request will contain this"); System.out.println("#control. Otherwise, false."); System.out.println("senderNonce.enable=true"); System.out.println(""); System.out.println("#senderNonce.id: sender nonce"); System.out.println("senderNonce.id="); System.out.println(""); - System.out - .println("#revRequest.enable: if true, then the request will contain this"); + System.out.println("#revRequest.enable: if true, then the request will contain this"); System.out.println("#control. Otherwise, false."); System.out.println("revRequest.enable=true"); System.out.println(""); - System.out - .println("#revRequest.nickname: The nickname for the revoke certificate"); + System.out.println("#revRequest.nickname: The nickname for the revoke certificate"); System.out.println("revRequest.nickname=newuser's 102504a ID"); System.out.println(""); - System.out - .println("#revRequest.issuer: The issuer name for the certificate being"); + System.out.println("#revRequest.issuer: The issuer name for the certificate being"); System.out.println("#revoked."); System.out.println("revRequest.issuer=cn=Certificate Manager,c=us"); System.out.println(""); - System.out - .println("#revRequest.serial: The serial number for the certificate being"); + System.out.println("#revRequest.serial: The serial number for the certificate being"); System.out.println("#revoked."); System.out.println("revRequest.serial=61"); System.out.println(""); - System.out - .println("#revRequest.reason: The reason for revoking this certificate: "); - System.out - .println("# unspecified, keyCompromise, caCompromise,"); - System.out - .println("# affiliationChanged, superseded, cessationOfOperation,"); - System.out - .println("# certificateHold, removeFromCRL"); + System.out.println("#revRequest.reason: The reason for revoking this certificate: "); + System.out.println("# unspecified, keyCompromise, caCompromise,"); + System.out.println("# affiliationChanged, superseded, cessationOfOperation,"); + System.out.println("# certificateHold, removeFromCRL"); System.out.println("revRequest.reason=unspecified"); System.out.println(""); System.out.println("#revRequest.sharedSecret: The sharedSecret"); @@ -448,35 +411,27 @@ public class CMCRequest { System.out.println("#revRequest.comment: The human readable comment"); System.out.println("revRequest.comment="); System.out.println(""); - System.out - .println("#revRequest.invalidityDatePresent: if true, the current time will be the"); - System.out - .println("# invalidityDate. If false, no invalidityDate"); + System.out.println("#revRequest.invalidityDatePresent: if true, the current time will be the"); + System.out.println("# invalidityDate. If false, no invalidityDate"); System.out.println("# is present."); System.out.println("revRequest.invalidityDatePresent=false"); System.out.println(""); - System.out - .println("#identityProof.enable: if true, then the request will contain"); + System.out.println("#identityProof.enable: if true, then the request will contain"); System.out.println("#this control. Otherwise, false."); System.out.println("identityProof.enable=true"); System.out.println(""); System.out.println("#identityProof.sharedSecret: Shared Secret"); System.out.println("identityProof.sharedSecret=testing"); System.out.println(""); - System.out - .println("#popLinkWitness.enable: if true, then the request will contain"); + System.out.println("#popLinkWitness.enable: if true, then the request will contain"); System.out.println("#this control. Otherwise, false."); - System.out - .println("#If you want to test this control, make sure to use CRMFPopClient "); - System.out - .println("# to generate the CRMF request which will include the "); - System.out - .println("#idPOPLinkWitness attribute in the controls section of the "); + System.out.println("#If you want to test this control, make sure to use CRMFPopClient "); + System.out.println("# to generate the CRMF request which will include the "); + System.out.println("#idPOPLinkWitness attribute in the controls section of the "); System.out.println("#CertRequest structure."); System.out.println("popLinkWitness.enable=false"); System.out.println(""); - System.out - .println("#LraPopWitness.enable: if true, then the request will contain this"); + System.out.println("#LraPopWitness.enable: if true, then the request will contain this"); System.out.println("#control. Otherwise, false."); System.out.println("LraPopWitness.enable=true"); System.out.println(""); @@ -486,44 +441,38 @@ public class CMCRequest { System.exit(1); } - private static int addLraPopWitnessAttr(int bpid, SEQUENCE seq, - String bodyPartIDs) { + private static int addLraPopWitnessAttr(int bpid, SEQUENCE seq, String bodyPartIDs) { StringTokenizer tokenizer = new StringTokenizer(bodyPartIDs, " "); - SEQUENCE bodyList = new SEQUENCE(); + SEQUENCE bodyList = new SEQUENCE(); while (tokenizer.hasMoreTokens()) { - String s = (String) tokenizer.nextToken(); + String s = (String)tokenizer.nextToken(); bodyList.addElement(new INTEGER(s)); } LraPopWitness lra = new LraPopWitness(new INTEGER(0), bodyList); - TaggedAttribute cont = new TaggedAttribute(new INTEGER(bpid++), - OBJECT_IDENTIFIER.id_cmc_lraPOPWitness, lra); - System.out - .println("Successfully create LRA POP witness control. bpid = " - + (bpid - 1)); - System.out.println(""); + TaggedAttribute cont = new TaggedAttribute(new + INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_lraPOPWitness, lra); + System.out.println("Successfully create LRA POP witness control. bpid = "+(bpid-1)); + System.out.println(""); seq.addElement(cont); return bpid; } - private static int addConfirmCertAttr(int bpid, SEQUENCE seq, - String confirmCertIssuer, String confirmCertSerial) { + private static int addConfirmCertAttr(int bpid, SEQUENCE seq, String confirmCertIssuer, + String confirmCertSerial) { try { INTEGER serial = new INTEGER(confirmCertSerial); X500Name issuername = new X500Name(confirmCertIssuer); byte[] issuerbyte = issuername.getEncoded(); ANY issuern = new ANY(issuerbyte); CMCCertId cmcCertId = new CMCCertId(issuern, serial, null); - TaggedAttribute cmcCertIdControl = new TaggedAttribute(new INTEGER( - bpid++), OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance, - cmcCertId); - System.out - .println("Successfully create confirm certificate acceptance control. bpid = " - + (bpid - 1)); - System.out.println(""); + TaggedAttribute cmcCertIdControl = new TaggedAttribute(new + INTEGER(bpid++), + OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance, cmcCertId); + System.out.println("Successfully create confirm certificate acceptance control. bpid = "+(bpid-1)); + System.out.println(""); seq.addElement(cmcCertIdControl); } catch (Exception e) { - System.out - .println("Error in creating confirm certificate acceptance control. Check the parameters."); + System.out.println("Error in creating confirm certificate acceptance control. Check the parameters."); System.exit(1); } return bpid; @@ -552,10 +501,10 @@ public class CMCRequest { System.exit(1); return RevRequest.unspecified; - } + } - private static int addIdentityProofAttr(int bpid, SEQUENCE seq, - SEQUENCE reqSequence, String sharedSecret) { + private static int addIdentityProofAttr(int bpid, SEQUENCE seq, SEQUENCE reqSequence, + String sharedSecret) { byte[] b = ASN1Util.encode(reqSequence); byte[] key = null; byte[] finalDigest = null; @@ -563,8 +512,8 @@ public class CMCRequest { MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1"); key = SHA1Digest.digest(sharedSecret.getBytes()); } catch (NoSuchAlgorithmException ex) { - System.out.println("CMCRequest::addIdentityProofAttr() - " - + "No such algorithm!"); + System.out.println( "CMCRequest::addIdentityProofAttr() - " + + "No such algorithm!" ); return -1; } @@ -576,33 +525,30 @@ public class CMCRequest { } catch (NoSuchAlgorithmException ex) { } - TaggedAttribute identityProof = new TaggedAttribute( - new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_identityProof, - new OCTET_STRING(finalDigest)); + TaggedAttribute identityProof = new TaggedAttribute(new + INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_identityProof, + new OCTET_STRING(finalDigest)); seq.addElement(identityProof); System.out.println("Identity Proof control: "); System.out.print(" Value: "); - for (int i = 0; i < finalDigest.length; i++) { - System.out.print(finalDigest[i] + " "); - } + for (int i=0; i 0) - sharedSecret = new OCTET_STRING( - revRequestSharedSecret.getBytes()); - if (revRequestComment.length() > 0) + sharedSecret = new OCTET_STRING(revRequestSharedSecret.getBytes()); + if (revRequestComment.length() > 0) comment = new UTF8String(revRequestComment); if (invalidityDatePresent.equals("true")) d = new GeneralizedTime(new Date()); - RevRequest revRequest = new RevRequest(new ANY( - subjectname.getEncoded()), snumber, reason, d, - sharedSecret, comment); + RevRequest revRequest = + new RevRequest(new ANY(subjectname.getEncoded()), snumber, + reason, d, sharedSecret, comment); int revokeBpid = bpid; TaggedAttribute revRequestControl = new TaggedAttribute( - new INTEGER(bpid++), - OBJECT_IDENTIFIER.id_cmc_revokeRequest, revRequest); + new INTEGER(bpid++), + OBJECT_IDENTIFIER.id_cmc_revokeRequest, revRequest); seq.addElement(revRequestControl); if (sharedSecret != null) { - System.out - .println("Successfully create revRequest control. bpid = " - + (bpid - 1)); + System.out.println("Successfully create revRequest control. bpid = "+(bpid-1)); System.out.println(""); - return bpid; + return bpid; } EncapsulatedContentInfo revokeContent = new EncapsulatedContentInfo( - OBJECT_IDENTIFIER.id_cct_PKIData, revRequestControl); + OBJECT_IDENTIFIER.id_cct_PKIData, revRequestControl); DigestAlgorithm digestAlg1 = null; SignatureAlgorithm signAlg1 = SignatureAlgorithm.RSASignatureWithSHA1Digest; java.security.PrivateKey revokePrivKey = null; @@ -643,14 +586,13 @@ public class CMCRequest { try { revokeCert = manager.findCertByNickname(nickname1); } catch (ObjectNotFoundException e) { - System.out.println("Certificate not found: " + nickname1); + System.out.println("Certificate not found: "+nickname1); System.exit(1); } revokePrivKey = manager.findPrivKeyByCert(revokeCert); - org.mozilla.jss.crypto.PrivateKey.Type signingKeyType1 = ((org.mozilla.jss.crypto.PrivateKey) revokePrivKey) - .getType(); - if (signingKeyType1 - .equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA)) + org.mozilla.jss.crypto.PrivateKey.Type signingKeyType1 = + ((org.mozilla.jss.crypto.PrivateKey) revokePrivKey).getType(); + if (signingKeyType1.equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA)) signAlg1 = SignatureAlgorithm.DSASignatureWithSHA1Digest; MessageDigest rSHADigest = null; @@ -666,79 +608,68 @@ public class CMCRequest { } catch (NoSuchAlgorithmException e) { } - ByteArrayInputStream bistream = new ByteArrayInputStream( - subjectname.getEncoded()); - Name iname = (Name) Name.getTemplate().decode(bistream); - IssuerAndSerialNumber ias1 = new IssuerAndSerialNumber(iname, - snumber); + ByteArrayInputStream bistream = + new ByteArrayInputStream(subjectname.getEncoded()); + Name iname = (Name)Name.getTemplate().decode(bistream); + IssuerAndSerialNumber ias1 = new IssuerAndSerialNumber(iname, snumber); SignerIdentifier rsi = new SignerIdentifier( - SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias1, null); + SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias1, null); SignerInfo signInfo1 = new SignerInfo(rsi, null, null, - OBJECT_IDENTIFIER.id_cct_PKIData, rdigest, signAlg1, + OBJECT_IDENTIFIER.id_cct_PKIData, rdigest, signAlg1, (org.mozilla.jss.crypto.PrivateKey) revokePrivKey); SET signInfos1 = new SET(); signInfos1.addElement(signInfo1); SET digestAlgs1 = new SET(); if (digestAlg1 != null) { - AlgorithmIdentifier ai1 = new AlgorithmIdentifier( - digestAlg1.toOID(), null); + AlgorithmIdentifier ai1 = new AlgorithmIdentifier(digestAlg1.toOID(), null); digestAlgs1.addElement(ai1); } - org.mozilla.jss.crypto.X509Certificate[] revokeCertChain = manager - .buildCertificateChain(revokeCert); + org.mozilla.jss.crypto.X509Certificate[] revokeCertChain = + manager.buildCertificateChain(revokeCert); SET certs1 = new SET(); - for (int i = 0; i < revokeCertChain.length; i++) { + for (int i=0; i 0) { int index = str.indexOf("="); String name = ""; - String val = ""; + String val = ""; if (index == -1) { - System.out.println("Error in configuration file: " - + str); + System.out.println("Error in configuration file: "+str); System.exit(1); } name = str.substring(0, index); - if (index != str.length() - 1) - val = str.substring(index + 1); + if (index != str.length()-1) + val = str.substring(index+1); if (name.equals("format")) { format = val; @@ -1018,15 +942,15 @@ public class CMCRequest { } StringTokenizer tokenizer = new StringTokenizer(ifilename, " "); - String[] ifiles = new String[num]; - for (int i = 0; i < num; i++) { - String ss = (String) tokenizer.nextToken(); + String[] ifiles = new String[num]; + for (int i=0; i - * * @version $Revision$, $Date$ - * + * */ -public class CMCResponse { +public class CMCResponse +{ public CMCResponse() { } @@ -61,18 +61,17 @@ public class CMCResponse { while (fis.available() > 0) fis.read(bb, 0, 10000); } catch (Exception e) { - System.out.println("Error reading the response. Exception: " - + e.toString()); + System.out.println("Error reading the response. Exception: "+e.toString()); System.exit(1); } try { ByteArrayInputStream bis = new ByteArrayInputStream(bb); - org.mozilla.jss.pkix.cms.ContentInfo cii = (org.mozilla.jss.pkix.cms.ContentInfo) org.mozilla.jss.pkix.cms.ContentInfo - .getTemplate().decode(bis); + org.mozilla.jss.pkix.cms.ContentInfo cii = (org.mozilla.jss.pkix.cms.ContentInfo) + org.mozilla.jss.pkix.cms.ContentInfo.getTemplate().decode(bis); - org.mozilla.jss.pkix.cms.SignedData cmcFullResp = (org.mozilla.jss.pkix.cms.SignedData) cii - .getInterpretedContent(); + org.mozilla.jss.pkix.cms.SignedData cmcFullResp = + (org.mozilla.jss.pkix.cms.SignedData)cii.getInterpretedContent(); String content = ""; if (cmcFullResp.hasCertificates()) { @@ -81,71 +80,62 @@ public class CMCResponse { for (int i = 0; i < numCerts; i++) { Certificate cert = (Certificate) certs.elementAt(i); - X509CertImpl certImpl = new X509CertImpl( - ASN1Util.encode(cert)); + X509CertImpl certImpl = new X509CertImpl(ASN1Util.encode(cert)); CertPrettyPrint print = new CertPrettyPrint(certImpl); content += print.toString(Locale.getDefault()); } } - + System.out.println("Certificates: "); System.out.println(content); System.out.println(""); EncapsulatedContentInfo ci = cmcFullResp.getContentInfo(); OBJECT_IDENTIFIER id = ci.getContentType(); - OBJECT_IDENTIFIER dataid = new OBJECT_IDENTIFIER( - "1.2.840.113549.1.7.1"); - if (!id.equals(OBJECT_IDENTIFIER.id_cct_PKIResponse) - && !id.equals(dataid)) { + OBJECT_IDENTIFIER dataid = new OBJECT_IDENTIFIER("1.2.840.113549.1.7.1"); + if (!id.equals(OBJECT_IDENTIFIER.id_cct_PKIResponse) && !id.equals(dataid)) { System.out.println("Invalid CMC Response Format"); - } + } if (!ci.hasContent()) return; OCTET_STRING content1 = ci.getContent(); - ByteArrayInputStream bbis = new ByteArrayInputStream( - content1.toByteArray()); - ResponseBody responseBody = (ResponseBody) (new ResponseBody.Template()) - .decode(bbis); + ByteArrayInputStream bbis = new ByteArrayInputStream(content1.toByteArray()); + ResponseBody responseBody = (ResponseBody) (new ResponseBody.Template()).decode(bbis); SEQUENCE controlSequence = responseBody.getControlSequence(); - + int numControls = controlSequence.size(); - System.out.println("Number of controls is " + numControls); + System.out.println("Number of controls is "+numControls); INTEGER bodyPartId = null; String error = ""; - for (int i = 0; i < numControls; i++) { - TaggedAttribute taggedAttr = (TaggedAttribute) controlSequence - .elementAt(i); + for (int i=0; i -i "); + System.out.println("Usage: CMCResponse -d -i "); } public static void main(String args[]) { @@ -238,11 +221,11 @@ public class CMCResponse { System.exit(1); } - for (int i = 0; i < args.length; i++) { + for (int i=0; i - * * @version $Revision$, $Date$ */ public class CMCRevoke { - public static final int ARGC = 7; + public static final int ARGC = 7; private static final String CERTDB = "cert8.db"; private static final String KEYDB = "key3.db"; public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----"; public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----"; - static String dValue = null, nValue = null, iValue = null, sValue = null, - mValue = null, hValue = null, cValue = null; + static String dValue = null, nValue = null, iValue = null, sValue = null, mValue = null, hValue = null, cValue = null; - public static final String CMS_BASE_CA_SIGNINGCERT_NOT_FOUND = "CA signing certificate not found"; + public static final String CMS_BASE_CA_SIGNINGCERT_NOT_FOUND="CA signing certificate not found"; public static final String PR_INTERNAL_TOKEN_NAME = "internal"; public static final String PR_REQUEST_CMC = "CMC"; - static String cleanArgs(String s) { + static String cleanArgs(String s) { if (s.startsWith("\"") && s.endsWith("\"")) return s.substring(1, s.length() - 2); else if (s.startsWith("\'") && s.endsWith("\'")) @@ -88,90 +89,94 @@ public class CMCRevoke { else return s; } - + /** - * Creates a new instance of CMCRevoke. + * Creates a new instance of CMCRevoke. */ - public static void main(String[] s) { - + public static void main(String[]s) { + FileOutputStream outputBlob = null; - + // default path is "." String mPath = "."; // default prefix is "" String mPrefix = ""; - + boolean bWrongParam = false; // (1) Check that two arguments were submitted to the program if (s.length != (ARGC) && s.length != (ARGC - 1)) { - + bWrongParam = true; System.out.println("Wrong number of parameters:" + s.length); - System.out.println("Usage: CMCRevoke " - + "-d

" + "-n " - + "-i " + "-s " - + "-m " + "-h " - + "-c "); + System.out.println("Usage: CMCRevoke " + + "-d " + + "-n " + + "-i " + + "-s " + + "-m " + + "-h " + + "-c "); for (int i = 0; i < s.length; i++) { System.out.println(i + ":" + s[i]); } - } else { + }else { int length; int i; - + length = s.length; for (i = 0; i < length; i++) { if (s[i].startsWith("-d")) { dValue = cleanArgs(s[i].substring(2)); - } else if (s[i].startsWith("-n")) { + } else if (s[i].startsWith("-n")) { nValue = cleanArgs(s[i].substring(2)); - } else if (s[i].startsWith("-i")) { + } else if (s[i].startsWith("-i")) { iValue = cleanArgs(s[i].substring(2)); - } else if (s[i].startsWith("-s")) { + } else if (s[i].startsWith("-s")) { sValue = cleanArgs(s[i].substring(2)); - } else if (s[i].startsWith("-m")) { + } else if (s[i].startsWith("-m")) { mValue = cleanArgs(s[i].substring(2)); - } else if (s[i].startsWith("-h")) { + } else if (s[i].startsWith("-h")) { hValue = cleanArgs(s[i].substring(2)); - } else if (s[i].startsWith("-c")) { + } else if (s[i].startsWith("-c")) { cValue = cleanArgs(s[i].substring(2)); } - + } // optional parameter if (cValue == null) cValue = new String(); - if (dValue == null || nValue == null || iValue == null - || sValue == null || mValue == null || hValue == null) + if (dValue == null || nValue == null || iValue == null || sValue == null || mValue == null || hValue == null) bWrongParam = true; - else if (dValue.length() == 0 || nValue.length() == 0 - || iValue.length() == 0 || sValue.length() == 0 - || mValue.length() == 0 || hValue.length() == 0) + else if (dValue.length() == 0 || nValue.length() == 0 || iValue.length() == 0 || + sValue.length() == 0 || mValue.length() == 0 || hValue.length() == 0) bWrongParam = true; - + if (bWrongParam == true) { - System.out.println("Usage: CMCRevoke " - + "-d " + "-n " - + "-i " + "-s " - + "-m " + "-h " - + "-c "); + System.out.println("Usage: CMCRevoke " + + "-d " + + "-n " + + "-i " + + "-s " + + "-m " + + "-h " + + "-c "); for (i = 0; i < s.length; i++) { System.out.println(i + ":" + s[i]); } System.exit(0); } - + try { // initialize CryptoManager mPath = dValue; System.out.println("cert/key prefix = " + mPrefix); System.out.println("path = " + mPath); - CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues( - mPath, mPrefix, mPrefix, "secmod.db"); + CryptoManager.InitializationValues vals = + new CryptoManager.InitializationValues(mPath, mPrefix, mPrefix, "secmod.db"); CryptoManager.initialize(vals); - + CryptoManager cm = CryptoManager.getInstance(); CryptoToken token = cm.getInternalKeyStorageToken(); Password pass = new Password(hValue.toCharArray()); @@ -180,16 +185,16 @@ public class CMCRevoke { CryptoStore store = token.getCryptoStore(); X509Certificate[] list = store.getCertificates(); X509Certificate signerCert = null; - + signerCert = cm.findCertByNickname(nValue); String outBlob = createRevokeReq(signerCert, cm, nValue); printCMCRevokeRequest(outBlob); - } catch (Exception e) { + }catch (Exception e) { e.printStackTrace(); System.exit(1); } - + return; } } @@ -197,53 +202,51 @@ public class CMCRevoke { /** * printout CMC revoke request in Base64 encoding to a file CMCRevoke.out *

- * * @param asciiBASE64Blob the ascii string of the request */ static void printCMCRevokeRequest(String asciiBASE64Blob) { - + // (6) Finally, print the actual CMCSigning blob to the - // specified output file + // specified output file FileOutputStream outputBlob = null; try { outputBlob = new FileOutputStream("CMCRevoke.out"); } catch (IOException e) { - System.out - .println("CMCSigning: unable to open file CMCRevoke.out for writing:\n" - + e); + System.out.println("CMCSigning: unable to open file CMCRevoke.out for writing:\n" + e); return; } - + System.out.println(HEADER); System.out.println(asciiBASE64Blob + TRAILER); try { asciiBASE64Blob = HEADER + "\n" + asciiBASE64Blob + TRAILER; outputBlob.write(asciiBASE64Blob.getBytes()); } catch (IOException e) { - System.out.println("CMCSigning: I/O error " - + "encountered during write():\n" + e); + System.out.println("CMCSigning: I/O error " + + "encountered during write():\n" + + e); } - + try { outputBlob.close(); } catch (IOException e) { - System.out.println("CMCSigning: Unexpected error " - + "encountered while attempting to close() " + "\n" + e); + System.out.println("CMCSigning: Unexpected error " + + "encountered while attempting to close() " + + "\n" + e); } } /** * getCertificate find the certicate inside the token by its nickname. *

- * * @param manager the CrytoManager * @param tokenname the name of the token. it's set to "internal". * @param nickname the nickname of the certificate inside the token. * @return the X509Certificate. */ - public static X509Certificate getCertificate(CryptoManager manager, - String tokenname, String nickname) throws NoSuchTokenException, + public static X509Certificate getCertificate(CryptoManager manager, String tokenname, + String nickname) throws NoSuchTokenException, Exception, TokenException { CryptoToken token = null; @@ -269,22 +272,19 @@ public class CMCRevoke { /** * createRevokeReq create and return the revocation request. *

- * - * @param signerCert the certificate of the authorized signer of the CMC - * revocation request. + * @param signerCert the certificate of the authorized signer of the CMC revocation request. * @param manager the crypto manger. * @param nValue the nickname of the certificate inside the token. * @return the CMC revocation request encoded in base64 */ - static String createRevokeReq(X509Certificate signerCert, - CryptoManager manager, String nValue) { + static String createRevokeReq(X509Certificate signerCert, CryptoManager manager, String nValue) { java.security.PrivateKey privKey = null; SignerIdentifier si = null; ContentInfo fullEnrollmentReq = null; String tokenname = "internal"; String asciiBASE64Blob = new String(); - + try { String hasSki = "true"; @@ -294,25 +294,23 @@ public class CMCRevoke { X509CertImpl impl = new X509CertImpl(certB); X500Name issuerName = (X500Name) impl.getIssuerDN(); byte[] issuerByte = issuerName.getEncoded(); - ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte); - + ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte); + Name issuer = (Name) Name.getTemplate().decode(istream); - IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, - new INTEGER(serialno.toString())); + IssuerAndSerialNumber ias = new IssuerAndSerialNumber(issuer, new INTEGER(serialno.toString())); - si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, - ias, null); + si = new SignerIdentifier(SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null); X509Certificate cert = getCertificate(manager, tokenname, nValue); - + privKey = manager.findPrivKeyByCert(cert); - if (privKey == null) { - System.out.println("CMCRevoke::createRevokeReq() - " - + "privKey is null!"); + if( privKey == null ) { + System.out.println( "CMCRevoke::createRevokeReq() - " + + "privKey is null!" ); return ""; } - int bpid = 1; + int bpid = 1; // Add some control sequence // Verisign has transactionID,senderNonce SEQUENCE controlSeq = new SEQUENCE(); @@ -330,8 +328,7 @@ public class CMCRevoke { } String sn = com.netscape.osutil.OSUtil.BtoA(dig); - TaggedAttribute senderNonce = new TaggedAttribute(new INTEGER( - bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce, + TaggedAttribute senderNonce = new TaggedAttribute(new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce, new OCTET_STRING(sn.getBytes())); controlSeq.addElement(senderNonce); @@ -339,42 +336,34 @@ public class CMCRevoke { Name subjectName = new Name(); subjectName.addCommonName(iValue); - org.mozilla.jss.pkix.cmmf.RevRequest lRevokeRequest = new org.mozilla.jss.pkix.cmmf.RevRequest( - new ANY((new X500Name(iValue)).getEncoded()), new INTEGER( - sValue), - // org.mozilla.jss.pkix.cmmf.RevRequest.unspecified, - new ENUMERATED((new Integer(mValue)).longValue()), - // new GeneralizedTime(new Date(lValue)), - new OCTET_STRING(hValue.getBytes()), new UTF8String( - cValue.toCharArray())); - // byte[] encoded = ASN1Util.encode(lRevokeRequest); - // org.mozilla.jss.asn1.ASN1Template template = new - // org.mozilla.jss.pkix.cmmf.RevRequest.Template(); - // org.mozilla.jss.pkix.cmmf.RevRequest revRequest = - // (org.mozilla.jss.pkix.cmmf.RevRequest) - // template.decode(new java.io.ByteArrayInputStream( - // encoded)); - + org.mozilla.jss.pkix.cmmf.RevRequest lRevokeRequest = new org.mozilla.jss.pkix.cmmf.RevRequest(new ANY((new X500Name(iValue)).getEncoded()), + new INTEGER(sValue), + //org.mozilla.jss.pkix.cmmf.RevRequest.unspecified, + new ENUMERATED((new Integer(mValue)). longValue()), + //new GeneralizedTime(new Date(lValue)), + new OCTET_STRING(hValue.getBytes()), + new UTF8String(cValue.toCharArray())); + //byte[] encoded = ASN1Util.encode(lRevokeRequest); + //org.mozilla.jss.asn1.ASN1Template template = new org.mozilla.jss.pkix.cmmf.RevRequest.Template(); + //org.mozilla.jss.pkix.cmmf.RevRequest revRequest = (org.mozilla.jss.pkix.cmmf.RevRequest) + // template.decode(new java.io.ByteArrayInputStream( + // encoded)); + ByteArrayOutputStream os = new ByteArrayOutputStream(); - // lRevokeRequest.encode(os); // khai - TaggedAttribute revokeRequestTag = new TaggedAttribute(new INTEGER( - bpid++), OBJECT_IDENTIFIER.id_cmc_revokeRequest, + //lRevokeRequest.encode(os); // khai + TaggedAttribute revokeRequestTag = new TaggedAttribute(new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_revokeRequest, lRevokeRequest); controlSeq.addElement(revokeRequestTag); - PKIData pkidata = new PKIData(controlSeq, new SEQUENCE(), - new SEQUENCE(), new SEQUENCE()); - - EncapsulatedContentInfo ci = new EncapsulatedContentInfo( - OBJECT_IDENTIFIER.id_cct_PKIData, pkidata); + PKIData pkidata = new PKIData(controlSeq, new SEQUENCE(), new SEQUENCE(), new SEQUENCE()); + + EncapsulatedContentInfo ci = new EncapsulatedContentInfo(OBJECT_IDENTIFIER.id_cct_PKIData, pkidata); // SHA1 is the default digest Alg for now. DigestAlgorithm digestAlg = null; SignatureAlgorithm signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest; - org.mozilla.jss.crypto.PrivateKey.Type signingKeyType = ((org.mozilla.jss.crypto.PrivateKey) privKey) - .getType(); + org.mozilla.jss.crypto.PrivateKey.Type signingKeyType = ((org.mozilla.jss.crypto.PrivateKey) privKey).getType(); - if (signingKeyType - .equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA)) + if (signingKeyType.equals(org.mozilla.jss.crypto.PrivateKey.Type.DSA)) signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest; MessageDigest SHADigest = null; byte[] digest = null; @@ -382,31 +371,28 @@ public class CMCRevoke { try { SHADigest = MessageDigest.getInstance("SHA1"); digestAlg = DigestAlgorithm.SHA1; - + ByteArrayOutputStream ostream = new ByteArrayOutputStream(); pkidata.encode((OutputStream) ostream); digest = SHADigest.digest(ostream.toByteArray()); } catch (NoSuchAlgorithmException e) { } - SignerInfo signInfo = new SignerInfo(si, null, null, - OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg, + SignerInfo signInfo = new SignerInfo(si, null, null, OBJECT_IDENTIFIER.id_cct_PKIData, digest, signAlg, (org.mozilla.jss.crypto.PrivateKey) privKey); SET signInfos = new SET(); signInfos.addElement(signInfo); - + SET digestAlgs = new SET(); if (digestAlg != null) { - AlgorithmIdentifier ai = new AlgorithmIdentifier( - digestAlg.toOID(), null); + AlgorithmIdentifier ai = new AlgorithmIdentifier(digestAlg.toOID(), null); digestAlgs.addElement(ai); } - - org.mozilla.jss.crypto.X509Certificate[] agentChain = manager - .buildCertificateChain(signerCert); + + org.mozilla.jss.crypto.X509Certificate[] agentChain = manager.buildCertificateChain(signerCert); SET certs = new SET(); for (int i = 0; i < agentChain.length; i++) { @@ -414,20 +400,19 @@ public class CMCRevoke { certs.addElement(certificate); } - SignedData req = new SignedData(digestAlgs, ci, certs, null, - signInfos); + SignedData req = new SignedData(digestAlgs, ci, certs, null, signInfos); fullEnrollmentReq = new ContentInfo(req); - + ByteArrayOutputStream bs = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bs); - + if (fullEnrollmentReq != null) { // format is PR_REQUEST_CMC fullEnrollmentReq.encode(os); ps.print(com.netscape.osutil.OSUtil.BtoA(os.toByteArray())); - // //fullEnrollmentReq.print(ps); // no header/trailer - } + ////fullEnrollmentReq.print(ps); // no header/trailer + } asciiBASE64Blob = bs.toString(); } catch (Exception e) { diff --git a/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java b/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java index 384f7ca49..c2d221731 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/CRMFPopClient.java @@ -69,51 +69,49 @@ import org.mozilla.jss.util.Password; import com.netscape.cmsutil.util.HMACDigest; + /** - * A command-line utility used to generate a Certificate Request Message Format - * (CRMF) request with proof of possesion (POP). - * + * A command-line utility used to generate a Certificate Request Message + * Format (CRMF) request with proof of possesion (POP). + * * Usage: - * *

  *     CRMFPopClient  TOKEN_PWD
  *                    PROFILE_NAME HOST PORT USER_NAME REQUESTOR_NAME
  *                    POP_OPTION
  *                    SUBJECT_DN [OUTPUT_CERT_REQ]
- * 
+ *
  *                    ---  or  ---
- * 
+ *
  *     CRMFPopClient  TOKEN_PWD
  *                    POP_OPTION
  *                    OUTPUT_CERT_REQ SUBJECT_DN
- * 
- * 
+ *
+ *
  *     where POP_OPTION can be [POP_SUCCESS or POP_FAIL or POP_NONE]
  * 
*

* Examples: - * *

  *     CRMFPopClient  password123
  *                    caEncUserCert host.example.com 1026 MyUid MyUid
  *                    [POP_SUCCESS or POP_FAIL or POP_NONE]
  *                    CN=MyTest,C=US,UID=MyUid
- * 
+ *
  *                    ---  or  ---
- * 
+ *
  *     CRMFPopClient  password123
  *                    caEncUserCert host.example.com 1026 joe joe
  *                    [POP_SUCCESS or POP_FAIL or POP_NONE]
  *                    CN=MyTest,C=US,UID=MyUid OUTPUT_CERT_REQ 
- * 
+ *
  *                    ---  or  ---
- * 
+ *
  *     CRMFPopClient  password123
  *                    [POP_SUCCESS or POP_FAIL or POP_NONE]
  *                    OUTPUT_CERT_REQ CN=MyTest,C=US,UID=MyUid
  * 
*

- * *

  * IMPORTANT:  The file "transport.txt" needs to be created to contain the
  *             transport certificate in its base64 encoded format.  This
@@ -121,549 +119,543 @@ import com.netscape.cmsutil.util.HMACDigest;
  *             in base64 encoded format with the header and footer removed.
  * 
*

- * * @version $Revision$, $Date$ */ -public class CRMFPopClient { - - private static void usage() { - System.out.println(""); - System.out - .println("Description: A command-line utility used to generate a"); - System.out - .println(" Certificate Request Message Format (CRMF)"); - System.out - .println(" request with proof of possesion (POP).\n\n"); - System.out.println("Usage:"); - System.out.println(""); - System.out.println(" CRMFPopClient TOKEN_PWD"); - System.out - .println(" PROFILE_NAME HOST PORT USER_NAME REQUESTOR_NAME"); - System.out.println(" POP_OPTION"); - System.out - .println(" SUBJECT_DN [OUTPUT_CERT_REQ] \n"); - System.out.println(" --- or ---\n"); - System.out.println(" CRMFPopClient TOKEN_PWD"); - System.out.println(" POP_OPTION"); - System.out.println(" OUTPUT_CERT_REQ SUBJECT_DN\n\n"); - System.out - .println(" where POP_OPTION can be [POP_SUCCESS or POP_FAIL or POP_NONE]\n\n"); - System.out.println("Examples:"); - System.out.println(""); - System.out.println(" CRMFPopClient password123"); - System.out - .println(" caEncUserCert host.example.com 1026 MyUid MyUid"); - System.out - .println(" [POP_SUCCESS or POP_FAIL or POP_NONE]"); - System.out.println(" CN=MyTest,C=US,UID=MyUid\n"); - System.out.println(" --- or ---\n"); - System.out.println(" CRMFPopClient password123"); - System.out - .println(" caEncUserCert host.example.com 1026 MyUid myUid"); - System.out - .println(" [POP_SUCCESS or POP_FAIL or POP_NONE]"); - System.out - .println(" CN=MyTest,C=US,UID=MyUid OUTPUT_CERT_REQ\n"); - System.out.println(" --- or ---\n"); - System.out.println(" CRMFPopClient password123"); - System.out - .println(" [POP_SUCCESS or POP_FAIL or POP_NONE]"); - System.out - .println(" OUTPUT_CERT_REQ CN=MyTest,C=US,UID=MyUid"); - System.out.println("\n"); - System.out - .println("IMPORTANT: The file \"transport.txt\" needs to be created to contain the"); - System.out - .println(" transport certificate in its base64 encoded format. This"); - System.out - .println(" file should consist of one line containing a single certificate"); - System.out - .println(" in base64 encoded format with the header and footer removed.\n"); - } - - private static int getRealArgsLength(String args[]) { - - int len = args.length; - - String curArg = ""; - int finalLen = len; - - for (int i = 0; i < len; i++) { - - curArg = args[i]; - // System.out.println("arg[" + i + "] " + curArg); - - if (curArg == null || curArg.equalsIgnoreCase("")) { - finalLen--; - } - +public class CRMFPopClient +{ + + private static void usage() + { + System.out.println(""); + System.out.println("Description: A command-line utility used to generate a"); + System.out.println(" Certificate Request Message Format (CRMF)"); + System.out.println(" request with proof of possesion (POP).\n\n"); + System.out.println("Usage:"); + System.out.println(""); + System.out.println(" CRMFPopClient TOKEN_PWD"); + System.out.println(" PROFILE_NAME HOST PORT USER_NAME REQUESTOR_NAME"); + System.out.println(" POP_OPTION"); + System.out.println(" SUBJECT_DN [OUTPUT_CERT_REQ] \n"); + System.out.println(" --- or ---\n"); + System.out.println(" CRMFPopClient TOKEN_PWD"); + System.out.println(" POP_OPTION"); + System.out.println(" OUTPUT_CERT_REQ SUBJECT_DN\n\n"); + System.out.println(" where POP_OPTION can be [POP_SUCCESS or POP_FAIL or POP_NONE]\n\n"); + System.out.println("Examples:"); + System.out.println(""); + System.out.println(" CRMFPopClient password123"); + System.out.println(" caEncUserCert host.example.com 1026 MyUid MyUid"); + System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]"); + System.out.println(" CN=MyTest,C=US,UID=MyUid\n"); + System.out.println(" --- or ---\n"); + System.out.println(" CRMFPopClient password123"); + System.out.println(" caEncUserCert host.example.com 1026 MyUid myUid"); + System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]"); + System.out.println(" CN=MyTest,C=US,UID=MyUid OUTPUT_CERT_REQ\n"); + System.out.println(" --- or ---\n"); + System.out.println(" CRMFPopClient password123"); + System.out.println(" [POP_SUCCESS or POP_FAIL or POP_NONE]"); + System.out.println(" OUTPUT_CERT_REQ CN=MyTest,C=US,UID=MyUid"); + System.out.println("\n"); + System.out.println("IMPORTANT: The file \"transport.txt\" needs to be created to contain the"); + System.out.println(" transport certificate in its base64 encoded format. This"); + System.out.println(" file should consist of one line containing a single certificate"); + System.out.println(" in base64 encoded format with the header and footer removed.\n"); } + private static int getRealArgsLength(String args[]) + { + + int len = args.length; + + String curArg = ""; + int finalLen = len; - // System.out.println("getRealArgsLength: returning " + finalLen); + for(int i = 0; i < len; i++) + { - if (finalLen < 0) - finalLen = 0; + curArg = args[i]; + // System.out.println("arg[" + i + "] " + curArg); - return finalLen; - } + if(curArg == null || curArg.equalsIgnoreCase("")) { + finalLen --; + } - public static void main(String args[]) { - String USER_PREFIX = "user"; + } - int argsLen = getRealArgsLength(args); + //System.out.println("getRealArgsLength: returning " + finalLen); - // System.out.println("args length " + argsLen); + if(finalLen < 0) + finalLen = 0; + + + return finalLen; - System.out.println("\n\nProof Of Possession Utility...."); - System.out.println(""); - if (argsLen == 0 - || (argsLen != 8 && argsLen != 9 && argsLen != 10 && argsLen != 4)) { - usage(); - return; } + public static void main(String args[]) + { + String USER_PREFIX = "user"; - String DB_DIR = "./"; - String TOKEN_PWD = args[0]; - int KEY_LEN = 1024; - int PORT = 0; - String USER_NAME = null; - String REQUESTOR_NAME = null; - String PROFILE_NAME = null; + int argsLen = getRealArgsLength(args); - String HOST = null; - String SUBJ_DN = null; + // System.out.println("args length " + argsLen); - if (argsLen >= 8) { - PROFILE_NAME = args[1]; - HOST = args[2]; - PORT = Integer.parseInt(args[3]); + System.out.println("\n\nProof Of Possession Utility...."); + System.out.println(""); - USER_NAME = args[4]; - REQUESTOR_NAME = args[5]; + if(argsLen == 0 || (argsLen != 8 && argsLen != 9 && argsLen !=10 && argsLen != 4)) + { + usage(); + return; + } - SUBJ_DN = args[7]; + String DB_DIR = "./"; + String TOKEN_PWD = args[0]; + int KEY_LEN = 1024; - } - String POP_OPTION = null; - String OUTPUT_CERT_REQ = null; + int PORT = 0; + String USER_NAME = null; + String REQUESTOR_NAME = null; + String PROFILE_NAME = null; + + String HOST = null; + String SUBJ_DN = null; + + if(argsLen >= 8) + { + PROFILE_NAME = args[1]; + HOST = args[2]; + + PORT = Integer.parseInt(args[3]); - if (argsLen == 4) - POP_OPTION = args[1]; - else - POP_OPTION = args[6]; + USER_NAME = args[4]; + REQUESTOR_NAME = args[5]; - int doServerHit = 1; + SUBJ_DN = args[7]; - if (argsLen >= 9) { - OUTPUT_CERT_REQ = args[8]; - } + } - if (argsLen == 4) { - doServerHit = 0; - OUTPUT_CERT_REQ = args[2]; - SUBJ_DN = args[3]; - } + String POP_OPTION = null; + String OUTPUT_CERT_REQ = null; - int dont_do_pop = 0; + if(argsLen == 4) + POP_OPTION = args[1]; + else + POP_OPTION = args[6]; - if (POP_OPTION.equals("POP_NONE")) { - dont_do_pop = 1; - } - URL url = null; - URLConnection conn = null; - InputStream is = null; - BufferedReader reader = null; - boolean success = false; - int num = 1; - long total_time = 0; - KeyPair pair = null; - - boolean foundTransport = false; - String transportCert = null; - try { - BufferedReader br = new BufferedReader(new FileReader( - "./transport.txt")); - transportCert = br.readLine(); - foundTransport = true; - } catch (Exception e) { - System.out - .println("ERROR: cannot find ./transport.txt, so no key archival"); - - return; - } + int doServerHit = 1; - try { - CryptoManager.initialize(DB_DIR); - } catch (Exception e) { - // it is ok if it is already initialized - System.out.println("INITIALIZATION ERROR: " + e.toString()); - // return; - } + if(argsLen >= 9) { + OUTPUT_CERT_REQ = args[8]; + } + + if(argsLen == 4) + { + doServerHit = 0; + OUTPUT_CERT_REQ = args[2]; + SUBJ_DN = args[3]; + } + + + int dont_do_pop = 0; + + if(POP_OPTION.equals("POP_NONE")) + { + dont_do_pop = 1; + } - try { - CryptoManager manager = CryptoManager.getInstance(); - String token_pwd = TOKEN_PWD; - CryptoToken token = manager.getInternalKeyStorageToken(); - Password password = new Password(token_pwd.toCharArray()); + URL url = null; + URLConnection conn = null; + InputStream is = null; + BufferedReader reader = null; + boolean success = false; + int num = 1; + long total_time = 0; + KeyPair pair = null; + + + boolean foundTransport = false; + String transportCert = null; try { - token.login(password); + BufferedReader br = new BufferedReader(new FileReader("./transport.txt")); + transportCert = br.readLine(); + foundTransport = true; } catch (Exception e) { - // System.out.println("login Exception: " + e.toString()); - if (!token.isLoggedIn()) { - token.initPassword(password, password); - } + System.out.println("ERROR: cannot find ./transport.txt, so no key archival"); + + return; + } + + + + try { + CryptoManager.initialize( DB_DIR ); + } catch (Exception e) { + // it is ok if it is already initialized + System.out.println("INITIALIZATION ERROR: " + e.toString()); + // return; } - System.out.println("."); // "done with cryptomanager"); - KeyPairGenerator kg = token - .getKeyPairGenerator(KeyPairAlgorithm.RSA); - kg.initialize(KEY_LEN); + try { + CryptoManager manager = CryptoManager.getInstance(); + String token_pwd = TOKEN_PWD; + CryptoToken token = manager.getInternalKeyStorageToken(); + Password password = new Password(token_pwd.toCharArray()); + try { + token.login(password); + } catch (Exception e) { + //System.out.println("login Exception: " + e.toString()); + if (!token.isLoggedIn()) { + token.initPassword(password, password); + } + } + + System.out.println("."); //"done with cryptomanager"); + + KeyPairGenerator kg = token.getKeyPairGenerator( + KeyPairAlgorithm.RSA); + kg.initialize(KEY_LEN); - String profileName = PROFILE_NAME; - pair = kg.genKeyPair(); + String profileName = PROFILE_NAME; + pair = kg.genKeyPair(); - System.out.println("."); // key pair generated"); + System.out.println("."); //key pair generated"); - // wrap private key - byte transport[] = com.netscape.osutil.OSUtil.AtoB(transportCert); + // wrap private key + byte transport[] = com.netscape.osutil.OSUtil.AtoB(transportCert); - X509Certificate tcert = manager.importCACertPackage(transport); + X509Certificate tcert = manager.importCACertPackage(transport); - byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; + byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1}; - KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3); - SymmetricKey sk = kg1.generate(); + KeyGenerator kg1 = token.getKeyGenerator(KeyGenAlgorithm.DES3); + SymmetricKey sk = kg1.generate(); - System.out.println("."); // before KeyWrapper"); + System.out.println("."); //before KeyWrapper"); - // wrap private key using session - KeyWrapper wrapper1 = token - .getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD); + // wrap private key using session + KeyWrapper wrapper1 = + token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD); - System.out.println("."); // key wrapper created"); + System.out.println("."); //key wrapper created"); - wrapper1.initWrap(sk, new IVParameterSpec(iv)); + wrapper1.initWrap(sk, new IVParameterSpec(iv)); - System.out.println("."); // key wrapper inited"); - byte key_data[] = wrapper1 - .wrap((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()); + System.out.println("."); //key wrapper inited"); + byte key_data[] = wrapper1.wrap((org.mozilla.jss.crypto.PrivateKey)pair.getPrivate()); - System.out.println("."); // key wrapper wrapped"); + System.out.println("."); //key wrapper wrapped"); - // wrap session using transport - KeyWrapper rsaWrap = token.getKeyWrapper(KeyWrapAlgorithm.RSA); + // wrap session using transport + KeyWrapper rsaWrap = token.getKeyWrapper( + KeyWrapAlgorithm.RSA); - System.out.println("."); // got rsaWrapper"); + System.out.println("."); //got rsaWrapper"); - rsaWrap.initWrap(tcert.getPublicKey(), null); + rsaWrap.initWrap(tcert.getPublicKey(), null); - System.out.println("."); // rsaWrap inited"); + System.out.println("."); //rsaWrap inited"); - byte session_data[] = rsaWrap.wrap(sk); + byte session_data[] = rsaWrap.wrap(sk); - System.out.println("."); // rsaWrapped"); + System.out.println("."); //rsaWrapped"); + try { + // create CRMF + CertTemplate certTemplate = new CertTemplate(); + certTemplate.setVersion(new INTEGER(2)); + + Name n1 = getJssName(SUBJ_DN); + + + Name n = new Name(); + + n.addCommonName("Me"); + n.addCountryName("US"); + n.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid"))); + + if(n1 != null) + certTemplate.setSubject(n1); + else + certTemplate.setSubject(n); + + certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair.getPublic())); + // set extension + AlgorithmIdentifier algS = new AlgorithmIdentifier(new OBJECT_IDENTIFIER("1.2.840.113549.3.7"), new OCTET_STRING(iv)); + EncryptedValue encValue = new EncryptedValue(null, algS, new BIT_STRING(session_data, 0),null, null,new BIT_STRING(key_data, 0)); + EncryptedKey key = new EncryptedKey(encValue); + PKIArchiveOptions opt = new PKIArchiveOptions(key); + SEQUENCE seq = new SEQUENCE(); + if (foundTransport) { + seq.addElement(new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"),opt)); + } + + + // Add idPOPLinkWitness control + String secretValue = "testing"; + byte[] key1 = null; + byte[] finalDigest = null; try { - // create CRMF - CertTemplate certTemplate = new CertTemplate(); - certTemplate.setVersion(new INTEGER(2)); - - Name n1 = getJssName(SUBJ_DN); - - Name n = new Name(); - - n.addCommonName("Me"); - n.addCountryName("US"); - n.addElement(new AVA(new OBJECT_IDENTIFIER( - "0.9.2342.19200300.100.1.1"), new PrintableString( - "MyUid"))); - - if (n1 != null) - certTemplate.setSubject(n1); - else - certTemplate.setSubject(n); - - certTemplate.setPublicKey(new SubjectPublicKeyInfo(pair - .getPublic())); - // set extension - AlgorithmIdentifier algS = new AlgorithmIdentifier( - new OBJECT_IDENTIFIER("1.2.840.113549.3.7"), - new OCTET_STRING(iv)); - EncryptedValue encValue = new EncryptedValue(null, algS, - new BIT_STRING(session_data, 0), null, null, - new BIT_STRING(key_data, 0)); - EncryptedKey key = new EncryptedKey(encValue); - PKIArchiveOptions opt = new PKIArchiveOptions(key); - SEQUENCE seq = new SEQUENCE(); - if (foundTransport) { - seq.addElement(new AVA(new OBJECT_IDENTIFIER( - "1.3.6.1.5.5.7.5.1.4"), opt)); - } + MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1"); + key1 = SHA1Digest.digest(secretValue.getBytes()); + } catch (NoSuchAlgorithmException ex) { + } - // Add idPOPLinkWitness control - String secretValue = "testing"; - byte[] key1 = null; - byte[] finalDigest = null; - try { - MessageDigest SHA1Digest = MessageDigest - .getInstance("SHA1"); - key1 = SHA1Digest.digest(secretValue.getBytes()); - } catch (NoSuchAlgorithmException ex) { - } +/* Example of adding the POP link witness control to CRMF */ +byte[] b = +{0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c, + 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c, + 0x51, 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45, + 0x61, 0x4f, 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31, + 0x32, 0x34, 0x35, 0x36, 0x55, 0x51, 0x48, 0x14, + 0x16, 0x29, 0x41, 0x42, 0x43, 0x7b, 0x63, 0x44, + 0x6a, 0x12, 0x6b, 0x3c, 0x4c, 0x3f, 0x00, 0x14, + 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, 0x5e, 0x69}; - /* Example of adding the POP link witness control to CRMF */ - byte[] b = { 0x10, 0x53, 0x42, 0x24, 0x1a, 0x2a, 0x35, 0x3c, - 0x7a, 0x52, 0x54, 0x56, 0x71, 0x65, 0x66, 0x4c, 0x51, - 0x34, 0x35, 0x23, 0x3c, 0x42, 0x43, 0x45, 0x61, 0x4f, - 0x6e, 0x43, 0x1e, 0x2a, 0x2b, 0x31, 0x32, 0x34, 0x35, - 0x36, 0x55, 0x51, 0x48, 0x14, 0x16, 0x29, 0x41, 0x42, - 0x43, 0x7b, 0x63, 0x44, 0x6a, 0x12, 0x6b, 0x3c, 0x4c, - 0x3f, 0x00, 0x14, 0x51, 0x61, 0x15, 0x22, 0x23, 0x5f, - 0x5e, 0x69 }; + try { + MessageDigest SHA1Digest = MessageDigest.getInstance("SHA1"); + HMACDigest hmacDigest = new HMACDigest(SHA1Digest, key1); + hmacDigest.update(b); + finalDigest = hmacDigest.digest(); + } catch (NoSuchAlgorithmException ex) { + } + - try { - MessageDigest SHA1Digest = MessageDigest - .getInstance("SHA1"); - HMACDigest hmacDigest = new HMACDigest(SHA1Digest, key1); - hmacDigest.update(b); - finalDigest = hmacDigest.digest(); - } catch (NoSuchAlgorithmException ex) { - } + OCTET_STRING ostr = new OCTET_STRING(finalDigest); + seq.addElement(new AVA(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr)); + CertRequest certReq = new CertRequest(new INTEGER(1), certTemplate, seq); - OCTET_STRING ostr = new OCTET_STRING(finalDigest); - seq.addElement(new AVA( - OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr)); - CertRequest certReq = new CertRequest(new INTEGER(1), - certTemplate, seq); + System.out.println("."); //CertRequest created"); - System.out.println("."); // CertRequest created"); - ByteArrayOutputStream bo = new ByteArrayOutputStream(); - certReq.encode(bo); - byte[] toBeVerified = bo.toByteArray(); + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + certReq.encode(bo); + byte[] toBeVerified = bo.toByteArray(); + + byte popdata[] = ASN1Util.encode(certReq); + byte signature[]; - byte popdata[] = ASN1Util.encode(certReq); - byte signature[]; + System.out.println("."); //CertRequest encoded"); - System.out.println("."); // CertRequest encoded"); + Signature signer = token.getSignatureContext( + SignatureAlgorithm.RSASignatureWithMD5Digest); - Signature signer = token - .getSignatureContext(SignatureAlgorithm.RSASignatureWithMD5Digest); + System.out.println("."); //signer created"); - System.out.println("."); // signer created"); + signer.initSign((org.mozilla.jss.crypto.PrivateKey)pair.getPrivate()); - signer.initSign((org.mozilla.jss.crypto.PrivateKey) pair - .getPrivate()); + System.out.println("."); //signer inited"); - System.out.println("."); // signer inited"); + System.out.println("."); //FAIL_OR_SUCC " + FAIL_OR_SUCC); - System.out.println("."); // FAIL_OR_SUCC " + FAIL_OR_SUCC); + if(POP_OPTION.equals("POP_SUCCESS")) + { + System.out.println("Generating Legal POP Data....."); + signer.update(toBeVerified); + } + else if(POP_OPTION.equals("POP_FAIL")) + { + System.out.println("Generating Illegal POP Data....."); + signer.update(iv); + } + else if(dont_do_pop == 1) + { + System.out.println("Generating NO POP Data....."); + } - if (POP_OPTION.equals("POP_SUCCESS")) { - System.out.println("Generating Legal POP Data....."); - signer.update(toBeVerified); - } else if (POP_OPTION.equals("POP_FAIL")) { - System.out.println("Generating Illegal POP Data....."); - signer.update(iv); - } else if (dont_do_pop == 1) { - System.out.println("Generating NO POP Data....."); - } + System.out.println("."); //signer updated"); - System.out.println("."); // signer updated"); + CertReqMsg crmfMsg = null; - CertReqMsg crmfMsg = null; + if(dont_do_pop == 0) + { + signature = signer.sign(); - if (dont_do_pop == 0) { - signature = signer.sign(); + System.out.println("Signature completed..."); + System.out.println(""); - System.out.println("Signature completed..."); - System.out.println(""); + + AlgorithmIdentifier algID = + new AlgorithmIdentifier(SignatureAlgorithm.RSASignatureWithMD5Digest.toOID(), null ); + POPOSigningKey popoKey = new POPOSigningKey(null,algID, new BIT_STRING(signature,0)); - AlgorithmIdentifier algID = new AlgorithmIdentifier( - SignatureAlgorithm.RSASignatureWithMD5Digest - .toOID(), - null); - POPOSigningKey popoKey = new POPOSigningKey(null, algID, - new BIT_STRING(signature, 0)); + ProofOfPossession pop = ProofOfPossession.createSignature(popoKey); - ProofOfPossession pop = ProofOfPossession - .createSignature(popoKey); + crmfMsg = new CertReqMsg(certReq, pop, null); - crmfMsg = new CertReqMsg(certReq, pop, null); + } + else + { + crmfMsg = new CertReqMsg(certReq, null, null); - } else { - crmfMsg = new CertReqMsg(certReq, null, null); + } - } + //crmfMsg.verify(); - // crmfMsg.verify(); + SEQUENCE s1 = new SEQUENCE(); + s1.addElement(crmfMsg); + byte encoded[] = ASN1Util.encode(s1); - SEQUENCE s1 = new SEQUENCE(); - s1.addElement(crmfMsg); - byte encoded[] = ASN1Util.encode(s1); + String Req1 = com.netscape.osutil.OSUtil.BtoA(encoded); - String Req1 = com.netscape.osutil.OSUtil.BtoA(encoded); + if(OUTPUT_CERT_REQ != null) + { + System.out.println("Generated Cert Request: ...... "); + System.out.println(""); - if (OUTPUT_CERT_REQ != null) { - System.out.println("Generated Cert Request: ...... "); - System.out.println(""); + System.out.println(Req1); + System.out.println(""); + System.out.println("End Request:"); - System.out.println(Req1); - System.out.println(""); - System.out.println("End Request:"); + if(doServerHit == 0) + return; + } + + String Req = URLEncoder.encode(Req1); - if (doServerHit == 0) - return; - } + // post PKCS10 + + url = new URL("http://" + HOST + ":" + PORT + "/ca/ee/ca/profileSubmit?cert_request_type=crmf&cert_request=" + Req + "&renewal=false&uid=" + USER_NAME + "&xmlOutput=false&&profileId=" + profileName + "&sn_uid=" + USER_NAME +"&SubId=profile&requestor_name="+ REQUESTOR_NAME); + //System.out.println("Posting " + url); - String Req = URLEncoder.encode(Req1); - - // post PKCS10 - - url = new URL( - "http://" - + HOST - + ":" - + PORT - + "/ca/ee/ca/profileSubmit?cert_request_type=crmf&cert_request=" - + Req + "&renewal=false&uid=" + USER_NAME - + "&xmlOutput=false&&profileId=" + profileName - + "&sn_uid=" + USER_NAME - + "&SubId=profile&requestor_name=" - + REQUESTOR_NAME); - // System.out.println("Posting " + url); - - System.out.println(""); - System.out.println("Server Response....."); - System.out.println("--------------------"); - System.out.println(""); - - long start_time = (new Date()).getTime(); - conn = url.openConnection(); - is = conn.getInputStream(); - reader = new BufferedReader(new InputStreamReader(is)); - String line = null; - while ((line = reader.readLine()) != null) { - System.out.println(line); - if (line.equals("CMS Enroll Request Success")) { - success = true; - System.out.println("Enrollment Successful: ......"); + System.out.println(""); + System.out.println("Server Response....."); + System.out.println("--------------------"); System.out.println(""); - } - } /* while */ - long end_time = (new Date()).getTime(); - total_time += (end_time - start_time); - } catch (Exception e) { - System.out.println("WARNING: " + e.toString()); - e.printStackTrace(); - } - } catch (Exception e) { - System.out.println("ERROR: " + e.toString()); - e.printStackTrace(); - } - } - static Name getJssName(String dn) { + long start_time = (new Date()).getTime(); + conn = url.openConnection(); + is = conn.getInputStream(); + reader = new BufferedReader(new InputStreamReader(is)); + String line = null; + while ((line = reader.readLine()) != null) { + System.out.println(line); + if (line.equals("CMS Enroll Request Success")) { + success = true; + System.out.println("Enrollment Successful: ......"); + System.out.println(""); + } + } /* while */ + long end_time = (new Date()).getTime(); + total_time += (end_time - start_time); + } catch (Exception e) { + System.out.println("WARNING: " + e.toString()); + e.printStackTrace(); + } + } catch (Exception e) { + System.out.println("ERROR: " + e.toString()); + e.printStackTrace(); + } + } - X500Name x5Name = null; + static Name getJssName(String dn) + { - try { - x5Name = new X500Name(dn); + X500Name x5Name = null; - } catch (IOException e) { + try { + x5Name= new X500Name(dn); - System.out.println("Illegal Subject Name: " + dn + " Error: " - + e.toString()); - System.out.println("Filling in default Subject Name......"); - return null; - } + } catch(IOException e) { - Name ret = new Name(); + System.out.println("Illegal Subject Name: " + dn + " Error: " + e.toString()); + System.out.println("Filling in default Subject Name......"); + return null; + } - netscape.security.x509.RDN[] names = null; + Name ret = new Name(); - names = x5Name.getNames(); + netscape.security.x509.RDN[] names = null; - int nameLen = x5Name.getNamesLength(); + names = x5Name.getNames(); - // System.out.println("x5Name len: " + nameLen); + int nameLen = x5Name.getNamesLength(); - netscape.security.x509.RDN cur = null; + // System.out.println("x5Name len: " + nameLen); - for (int i = 0; i < nameLen; i++) { - cur = names[i]; + netscape.security.x509.RDN cur = null; - String rdnStr = cur.toString(); + for(int i = 0; i < nameLen ; i++) + { + cur = names[i]; - String[] split = rdnStr.split("="); + String rdnStr = cur.toString(); - if (split.length != 2) - continue; - try { + String[] split = rdnStr.split("="); + + if(split.length != 2) + continue; + + try { - if (split[0].equals("UID")) { + if(split[0].equals("UID")) + { - ret.addElement(new AVA(new OBJECT_IDENTIFIER( - "0.9.2342.19200300.100.1.1"), new PrintableString( - split[1]))); - // System.out.println("UID found : " + split[1]); + ret.addElement(new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString(split[1]))); + // System.out.println("UID found : " + split[1]); } - if (split[0].equals("C")) { - ret.addCountryName(split[1]); - // System.out.println("C found : " + split[1]); - continue; + if(split[0].equals("C")) + { + ret.addCountryName(split[1]); + // System.out.println("C found : " + split[1]); + continue; } - if (split[0].equals("CN")) { - ret.addCommonName(split[1]); - // System.out.println("CN found : " + split[1]); - continue; + if(split[0].equals("CN")) + { + ret.addCommonName(split[1]); + // System.out.println("CN found : " + split[1]); + continue; } - if (split[0].equals("L")) { - ret.addLocalityName(split[1]); - // System.out.println("L found : " + split[1]); - continue; + if(split[0].equals("L")) + { + ret.addLocalityName(split[1]); + // System.out.println("L found : " + split[1]); + continue; } - if (split[0].equals("O")) { - ret.addOrganizationName(split[1]); - // System.out.println("O found : " + split[1]); - continue; + if(split[0].equals("O")) + { + ret.addOrganizationName(split[1]); + // System.out.println("O found : " + split[1]); + continue; } - if (split[0].equals("ST")) { - ret.addStateOrProvinceName(split[1]); - // System.out.println("ST found : " + split[1]); - continue; + if(split[0].equals("ST")) + { + ret.addStateOrProvinceName(split[1]); + // System.out.println("ST found : " + split[1]); + continue; + } + + if(split[0].equals("OU")) + { + ret.addOrganizationalUnitName(split[1]); + // System.out.println("OU found : " + split[1]); + continue; } + } catch (Exception e) { + System.out.println("Error constructing RDN: " + rdnStr + " Error: " + e.toString()); - if (split[0].equals("OU")) { - ret.addOrganizationalUnitName(split[1]); - // System.out.println("OU found : " + split[1]); continue; } - } catch (Exception e) { - System.out.println("Error constructing RDN: " + rdnStr - + " Error: " + e.toString()); - continue; + } - } + return ret; - return ret; - } + } } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java b/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java index 419f8f01f..20dfb42ef 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/DRMTool.java @@ -66,31 +66,30 @@ import org.mozilla.jss.pkcs11.PK11PubKey; import org.mozilla.jss.util.Password; /** - * The DRMTool class is a utility program designed to operate on an LDIF file to - * perform one or more of the following tasks: - * + * The DRMTool class is a utility program designed to operate on an LDIF file + * to perform one or more of the following tasks: *

  *     (A) Use a new storage key (e. g. - a 2048-bit key to replace a
  *         1024-bit key) to rewrap the existing triple DES symmetric key
  *         that was used to wrap a user's private key.
- * 
+ *
  *         STARTING INVENTORY:
- * 
+ *
  *             (1) a DRMTOOL configuration file containing DRM LDIF record
  *                 types and the processing status of their associated fields
- * 
+ *
  *             (2) an LDIF file containing 'exported' DRM data
  *                 (referred to as the "source" DRM)
- * 
+ *
  *                 NOTE:  If this LDIF file contains data that was originally
  *                        from a DRM instance that was prior to RHCS 8, it
  *                        must have previously undergone the appropriate
  *                        migration steps.
- * 
+ *
  *             (3) the NSS security databases (e. g. - cert8.db, key3.db,
  *                 and secmod.db) associated with the data contained in
  *                 the source LDIF file
- * 
+ *
  *                 NOTE:  If the storage key was located on an HSM, then the
  *                        HSM must be available to the machine on which the
  *                        DRMTool is being executed (since the RSA private
@@ -99,302 +98,301 @@ import org.mozilla.jss.util.Password;
  *                        password may be required to unlock access to
  *                        this key (e. g. - which may be located in
  *                        the source DRM's 'password.conf' file).
- * 
+ *
  *             (4) a file containing the ASCII BASE-64 storage certificate
  *                 from the DRM instance for which the output LDIF file is
  *                 intended (referred to as the "target")
- * 
+ *
  *         ENDING INVENTORY:
- * 
+ *
  *             (1) all items listed in the STARTING INVENTORY (unchanged)
- * 
+ *
  *             (2) a log file containing information suitable for audit
  *                 purposes
- * 
+ *
  *             (3) an LDIF file containing the revised data suitable for
  *                 'import' into a new DRM (referred to as the "target" DRM)
- * 
+ *
  *         DRMTool PARAMETERS:
- * 
+ *
  *             (1) the name of the DRMTOOL configuration file containing
  *                 DRM LDIF record types and the processing status of their
  *                 associated fields
- * 
+ *
  *             (2) the name of the input LDIF file containing data which was
  *                 'exported' from the source DRM instance
- * 
+ *
  *             (3) the name of the output LDIF file intended to contain the
  *                 revised data suitable for 'import' to a target DRM instance
- * 
+ *
  *             (4) the name of the log file that may be used for auditing
  *                 purposes
- * 
+ *
  *             (5) the path to the security databases that were used by
  *                 the source DRM instance
- * 
+ *
  *             (6) the name of the token that was used by
  *                 the source DRM instance
- * 
+ *
  *             (7) the name of the storage certificate that was used by
  *                 the source DRM instance
- * 
+ *
  *             (8) the name of the file containing the ASCII BASE-64 storage
  *                 certificate from the target DRM instance for which the
  *                 output LDIF file is intended
- * 
+ *
  *             (9) OPTIONALLY, the name of a file which ONLY contains the
  *                 password needed to access the source DRM instance's
  *                 security databases
- * 
+ *
  *            (10) OPTIONALLY, choose to change the specified source DRM naming
  *                 context to the specified target DRM naming context
- * 
+ *
  *            (11) OPTIONALLY, choose to ONLY process CA enrollment requests,
  *                 CA recovery requests, CA key records, TPS netkeyKeygen
  *                 enrollment requests, TPS recovery requests, and
  *                 TPS key records
- * 
+ *
  *         DATA FIELDS AFFECTED (using default config file values):
- * 
+ *
  *             (1) CA DRM enrollment request
- * 
+ *
  *                 (a) dateOfModify
  *                 (b) extdata-requestnotes
- * 
+ *
  *             (2) CA DRM key record
- * 
+ *
  *                 (a) dateOfModify
  *                 (b) privateKeyData
- * 
+ *
  *             (3) CA DRM recovery request
- * 
+ *
  *                 (a) dateOfModify
  *                 (b) extdata-requestnotes (NEW)
- * 
+ *
  *             (4) TPS DRM netkeyKeygen (enrollment) request
- * 
+ *
  *                 (a) dateOfModify
  *                 (b) extdata-requestnotes (NEW)
- * 
+ *
  *             (5) TPS DRM key record
- * 
+ *
  *                 (a) dateOfModify
  *                 (b) privateKeyData
- * 
+ *
  *             (6) TPS DRM recovery request
- * 
+ *
  *                 (a) dateOfModify
  *                 (b) extdata-requestnotes (NEW)
- * 
+ *
  *     (B) Specify an ID offset to append to existing numeric data
  *         (e. g. - to renumber data for use in DRM consolidation efforts).
- * 
+ *
  *         STARTING INVENTORY:
- * 
+ *
  *             (1) a DRMTOOL configuration file containing DRM LDIF record
  *                 types and the processing status of their associated fields
- * 
+ *
  *             (2) an LDIF file containing 'exported' DRM data
  *                 (referred to as the "source" DRM)
- * 
+ *
  *                 NOTE:  If this LDIF file contains data that was originally
  *                        from a DRM instance that was prior to RHCS 8, it
  *                        must have previously undergone the appropriate
  *                        migration steps.
- * 
+ *
  *         ENDING INVENTORY:
- * 
+ *
  *             (1) all items listed in the STARTING INVENTORY (unchanged)
- * 
+ *
  *             (2) a log file containing information suitable for audit
  *                 purposes
- * 
+ *
  *             (3) an LDIF file containing the revised data suitable for
  *                 'import' into a new DRM (referred to as the "target" DRM)
- * 
+ *
  *         DRMTool PARAMETERS:
- * 
+ *
  *             (1) the name of the DRMTOOL configuration file containing
  *                 DRM LDIF record types and the processing status of their
  *                 associated fields
- * 
+ *
  *             (2) the name of the input LDIF file containing data which was
  *                 'exported' from the source DRM instance
- * 
+ *
  *             (3) the name of the output LDIF file intended to contain the
  *                 revised data suitable for 'import' to a target DRM instance
- * 
+ *
  *             (4) the name of the log file that may be used for auditing
  *                 purposes
- * 
+ *
  *             (5) a large numeric ID offset (mask) to be appended to existing
  *                 numeric data in the source DRM instance's LDIF file
- * 
+ *
  *             (6) OPTIONALLY, choose to change the specified source DRM naming
  *                 context to the specified target DRM naming context
- * 
+ *
  *             (7) OPTIONALLY, choose to ONLY process CA enrollment requests,
  *                 CA recovery requests, CA key records, TPS netkeyKeygen
  *                 enrollment requests, TPS recovery requests, and
  *                 TPS key records
- * 
+ *
  *         DATA FIELDS AFFECTED (using default config file values):
- * 
+ *
  *             (1) CA DRM enrollment request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-keyrecord
  *                 (d) extdata-requestnotes
  *                 (e) requestId
- * 
+ *
  *             (2) CA DRM key record
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) serialno
- * 
+ *
  *             (3) CA DRM recovery request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-requestid
  *                 (d) extdata-requestnotes (NEW)
  *                 (e) extdata-serialnumber
  *                 (f) requestId
- * 
+ *
  *             (4) TPS DRM netkeyKeygen (enrollment) request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-keyrecord
  *                 (d) extdata-requestid
  *                 (e) extdata-requestnotes (NEW)
  *                 (f) requestId
- * 
+ *
  *             (5) TPS DRM key record
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) serialno
- * 
+ *
  *             (6) TPS DRM recovery request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-requestid
  *                 (d) extdata-requestnotes (NEW)
  *                 (e) extdata-serialnumber
  *                 (f) requestId
- * 
+ *
  *     (C) Specify an ID offset to be removed from existing numeric data
  *         (e. g. - to undo renumbering used in DRM consolidation efforts).
- * 
+ *
  *         STARTING INVENTORY:
- * 
+ *
  *             (1) a DRMTOOL configuration file containing DRM LDIF record
  *                 types and the processing status of their associated fields
- * 
+ *
  *             (2) an LDIF file containing 'exported' DRM data
  *                 (referred to as the "source" DRM)
- * 
+ *
  *                 NOTE:  If this LDIF file contains data that was originally
  *                        from a DRM instance that was prior to RHCS 8, it
  *                        must have previously undergone the appropriate
  *                        migration steps.
- * 
+ *
  *         ENDING INVENTORY:
- * 
+ *
  *             (1) all items listed in the STARTING INVENTORY (unchanged)
- * 
+ *
  *             (2) a log file containing information suitable for audit
  *                 purposes
- * 
+ *
  *             (3) an LDIF file containing the revised data suitable for
  *                 'import' into a new DRM (referred to as the "target" DRM)
- * 
+ *
  *         DRMTool PARAMETERS:
- * 
+ *
  *             (1) the name of the DRMTOOL configuration file containing
  *                 DRM LDIF record types and the processing status of their
  *                 associated fields
- * 
+ *
  *             (2) the name of the input LDIF file containing data which was
  *                 'exported' from the source DRM instance
- * 
+ *
  *             (3) the name of the output LDIF file intended to contain the
  *                 revised data suitable for 'import' to a target DRM instance
- * 
+ *
  *             (4) the name of the log file that may be used for auditing
  *                 purposes
- * 
+ *
  *             (5) a large numeric ID offset (mask) to be removed from existing
  *                 numeric data in the source DRM instance's LDIF file
- * 
+ *
  *             (6) OPTIONALLY, choose to change the specified source DRM naming
  *                 context to the specified target DRM naming context
- * 
+ *
  *             (7) OPTIONALLY, choose to ONLY process CA enrollment requests,
  *                 CA recovery requests, CA key records, TPS netkeyKeygen
  *                 enrollment requests, TPS recovery requests, and
  *                 TPS key records
- * 
+ *
  *         DATA FIELDS AFFECTED (using default config file values):
- * 
+ *
  *             (1) CA DRM enrollment request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-keyrecord
  *                 (d) extdata-requestnotes
  *                 (e) requestId
- * 
+ *
  *             (2) CA DRM key record
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) serialno
- * 
+ *
  *             (3) CA DRM recovery request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-requestid
  *                 (d) extdata-requestnotes (NEW)
  *                 (e) extdata-serialnumber
  *                 (f) requestId
- * 
+ *
  *             (4) TPS DRM netkeyKeygen (enrollment) request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-keyrecord
  *                 (d) extdata-requestid
  *                 (e) extdata-requestnotes (NEW)
  *                 (f) requestId
- * 
+ *
  *             (5) TPS DRM key record
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) serialno
- * 
+ *
  *             (6) TPS DRM recovery request
- * 
+ *
  *                 (a) cn
  *                 (b) dateOfModify
  *                 (c) extdata-requestid
  *                 (d) extdata-requestnotes (NEW)
  *                 (e) extdata-serialnumber
  *                 (f) requestId
- * 
+ *
  * 
- * + * *

* DRMTool may be invoked as follows: - * *

- * 
+ *
  *    DRMTool
  *    -drmtool_config_file <path + drmtool config file>
  *    -source_ldif_file <path + source ldif file>
@@ -410,95 +408,96 @@ import org.mozilla.jss.util.Password;
  *    [-source_drm_naming_context '<original source DRM naming context>']
  *    [-target_drm_naming_context '<renamed target DRM naming context>']
  *    [-process_requests_and_key_records_only]
- * 
+ *
  *    where the following options are 'Mandatory':
- * 
+ *
  *    -drmtool_config_file <path + drmtool config file>
  *    -source_ldif_file <path + source ldif file>
  *    -target_ldif_file <path + target ldif file>
  *    -log_file <path + log file>
- * 
+ *
  *    AND at least ONE of the following are a 'Mandatory' set of options:
- * 
+ *
  *        (a) options for using a new storage key for rewrapping:
- * 
+ *
  *            [-source_pki_security_database_path
  *             <path to PKI source database>]
  *            [-source_storage_token_name '<source token>']
  *            [-source_storage_certificate_nickname '<source nickname>']
  *            [-target_storage_certificate_file
  *             <path to target certificate file>]
- * 
+ *
  *            AND OPTIONALLY, specify the name of a file which ONLY contains
  *            the password needed to access the source DRM instance's
  *            security databases:
- * 
+ *
  *            [-source_pki_security_database_pwdfile
  *             <path to PKI password file>]
- * 
+ *
  *            AND OPTIONALLY, rename source DRM naming context --> target
  *            DRM naming context:
- * 
+ *
  *            [-source_drm_naming_context '<source DRM naming context>']
  *            [-target_drm_naming_context '<target DRM naming context>']
- * 
+ *
  *            AND OPTIONALLY, process requests and key records ONLY:
- * 
+ *
  *            [-process_requests_and_key_records_only]
- * 
+ *
  *        (b) option for appending the specified numeric ID offset
  *            to existing numerical data:
- * 
+ *
  *            [-append_id_offset <numeric offset>]
- * 
+ *
  *            AND OPTIONALLY, rename source DRM naming context --> target
  *            DRM naming context:
- * 
+ *
  *            [-source_drm_naming_context '<source DRM naming context>']
  *            [-target_drm_naming_context '<target DRM naming context>']
- * 
+ *
  *            AND OPTIONALLY, process requests and key records ONLY:
- * 
+ *
  *            [-process_requests_and_key_records_only]
- * 
+ *
  *        (c) option for removing the specified numeric ID offset
  *            from existing numerical data:
- * 
+ *
  *            AND OPTIONALLY, rename source DRM naming context --> target
  *            DRM naming context:
- * 
+ *
  *            [-source_drm_naming_context '<source DRM naming context>']
  *            [-target_drm_naming_context '<target DRM naming context>']
- * 
+ *
  *            [-remove_id_offset <numeric offset>]
- * 
+ *
  *            AND OPTIONALLY, process requests and key records ONLY:
- * 
+ *
  *            [-process_requests_and_key_records_only]
- * 
+ *
  *        (d) (a) rewrap AND (b) append ID offset
  *            [AND OPTIONALLY, rename source DRM naming context --> target
  *            DRM naming context]
  *            [AND OPTIONALLY process requests and key records ONLY]
- * 
+ *
  *        (e) (a) rewrap AND (c) remove ID offset
  *            [AND OPTIONALLY, rename source DRM naming context --> target
  *            DRM naming context]
  *            [AND OPTIONALLY process requests and key records ONLY]
- * 
+ *
  *        NOTE:  Options (b) and (c) are mutually exclusive!
- * 
+ *
  * 
- * + * * @author mharmsen * @version $Revision$, $Date$ */ -public class DRMTool { +public class DRMTool +{ /*************/ /* Constants */ /*************/ - // Constants: Miscellaneous + // Constants: Miscellaneous private static final boolean FAILURE = false; private static final boolean SUCCESS = true; private static final String COLON = ":"; @@ -513,14 +512,17 @@ public class DRMTool { private static final String SPACE = " "; private static final String TIC = "'"; - // Constants: Calendar + + // Constants: Calendar private static final String DATE_OF_MODIFY_PATTERN = "yyyyMMddHHmmss'Z'"; private static final String LOGGING_DATE_PATTERN = "dd/MMM/yyyy:HH:mm:ss z"; - // Constants: PKCS #11 Information + + // Constants: PKCS #11 Information private static final String INTERNAL_TOKEN = "Internal Key Storage Token"; - // Constants: Command-line Options + + // Constants: Command-line Options private static final int ID_OFFSET_NAME_VALUE_PAIRS = 1; private static final int PWDFILE_NAME_VALUE_PAIRS = 1; private static final int NAMING_CONTEXT_NAME_VALUE_PAIRS = 2; @@ -530,136 +532,212 @@ public class DRMTool { private static final int REWRAP_ARGS = 16; private static final int REWRAP_AND_ID_OFFSET_ARGS = 18; - // Constants: Command-line Options (Mandatory) - private static final String DRM_TOOL = "DRMTool"; - - private static final String DRMTOOL_CFG_FILE = "-drmtool_config_file"; - - private static final String DRMTOOL_CFG_DESCRIPTION = " "; - - private static final String DRMTOOL_CFG_FILE_EXAMPLE = DRMTOOL_CFG_FILE - + " " + "/usr/share/pki/java-tools/DRMTool.cfg"; - - private static final String SOURCE_LDIF_FILE = "-source_ldif_file"; - - private static final String SOURCE_LDIF_DESCRIPTION = " "; - - private static final String SOURCE_LDIF_FILE_EXAMPLE = SOURCE_LDIF_FILE - + " " + "/export/pki/source.ldif"; - - private static final String TARGET_LDIF_FILE = "-target_ldif_file"; - - private static final String TARGET_LDIF_DESCRIPTION = " "; - - private static final String TARGET_LDIF_FILE_EXAMPLE = TARGET_LDIF_FILE - + " " + "/export/pki/target.ldif"; - - private static final String LOG_FILE = "-log_file"; - - private static final String LOG_DESCRIPTION = " "; - - private static final String LOG_FILE_EXAMPLE = LOG_FILE + " " - + "/export/pki/DRMTool.log"; - - // Constants: Command-line Options (Rewrap) - private static final String SOURCE_NSS_DB_PATH = "-source_pki_security_database_path"; - - private static final String SOURCE_NSS_DB_DESCRIPTION = " "; - - private static final String SOURCE_NSS_DB_PATH_EXAMPLE = SOURCE_NSS_DB_PATH - + " " + "/export/pki"; - - private static final String SOURCE_STORAGE_TOKEN_NAME = "-source_storage_token_name"; - - private static final String SOURCE_STORAGE_TOKEN_DESCRIPTION = " "; - - private static final String SOURCE_STORAGE_TOKEN_NAME_EXAMPLE = SOURCE_STORAGE_TOKEN_NAME - + " " + TIC + "Internal Key Storage Token" + TIC; - - private static final String SOURCE_STORAGE_CERT_NICKNAME = "-source_storage_certificate_nickname"; - - private static final String SOURCE_STORAGE_CERT_NICKNAME_DESCRIPTION = " "; - - private static final String SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE = SOURCE_STORAGE_CERT_NICKNAME - + " " + TIC + "storageCert cert-pki-kra" + TIC; - - private static final String TARGET_STORAGE_CERTIFICATE_FILE = "-target_storage_certificate_file"; - - private static final String TARGET_STORAGE_CERTIFICATE_DESCRIPTION = " "; - - private static final String TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE = TARGET_STORAGE_CERTIFICATE_FILE - + " " + "/export/pki/target_storage.cert"; - private static final String SOURCE_NSS_DB_PWDFILE = "-source_pki_security_database_pwdfile"; - - private static final String SOURCE_NSS_DB_PWDFILE_DESCRIPTION = " "; - - private static final String SOURCE_NSS_DB_PWDFILE_EXAMPLE = SOURCE_NSS_DB_PWDFILE - + " " + "/export/pki/pwdfile"; - - // Constants: Command-line Options (ID Offset) - private static final String APPEND_ID_OFFSET = "-append_id_offset"; - - private static final String APPEND_ID_OFFSET_DESCRIPTION = " "; - - private static final String APPEND_ID_OFFSET_EXAMPLE = APPEND_ID_OFFSET - + " " + "100000000000"; - - private static final String REMOVE_ID_OFFSET = "-remove_id_offset"; - - private static final String REMOVE_ID_OFFSET_DESCRIPTION = " "; - - private static final String REMOVE_ID_OFFSET_EXAMPLE = REMOVE_ID_OFFSET - + " " + "100000000000"; - - // Constants: Command-line Options - private static final String SOURCE_DRM_NAMING_CONTEXT = "-source_drm_naming_context"; - - private static final String SOURCE_DRM_NAMING_CONTEXT_DESCRIPTION = " "; - - private static final String SOURCE_DRM_NAMING_CONTEXT_EXAMPLE = SOURCE_DRM_NAMING_CONTEXT - + " " + TIC + "alpha.example.com-pki-kra" + TIC; - - private static final String TARGET_DRM_NAMING_CONTEXT = "-target_drm_naming_context"; - - private static final String TARGET_DRM_NAMING_CONTEXT_DESCRIPTION = " "; - - private static final String TARGET_DRM_NAMING_CONTEXT_EXAMPLE = TARGET_DRM_NAMING_CONTEXT - + " " + TIC + "omega.example.com-pki-kra" + TIC; - - private static final String PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY = "-process_requests_and_key_records_only"; + // Constants: Command-line Options (Mandatory) + private static final String DRM_TOOL = "DRMTool"; - // Constants: DRMTOOL Config File + private static final String + DRMTOOL_CFG_FILE = "-drmtool_config_file"; + + private static final String + DRMTOOL_CFG_DESCRIPTION = " "; + + private static final String + DRMTOOL_CFG_FILE_EXAMPLE = DRMTOOL_CFG_FILE + + " " + + "/usr/share/pki/java-tools/DRMTool.cfg"; + + private static final String + SOURCE_LDIF_FILE = "-source_ldif_file"; + + private static final String + SOURCE_LDIF_DESCRIPTION = " "; + + private static final String + SOURCE_LDIF_FILE_EXAMPLE = SOURCE_LDIF_FILE + + " " + + "/export/pki/source.ldif"; + + private static final String + TARGET_LDIF_FILE = "-target_ldif_file"; + + private static final String + TARGET_LDIF_DESCRIPTION = " "; + + private static final String + TARGET_LDIF_FILE_EXAMPLE = TARGET_LDIF_FILE + + " " + + "/export/pki/target.ldif"; + + private static final String + LOG_FILE = "-log_file"; + + private static final String + LOG_DESCRIPTION = " "; + + private static final String + LOG_FILE_EXAMPLE = LOG_FILE + + " " + + "/export/pki/DRMTool.log"; + + + // Constants: Command-line Options (Rewrap) + private static final String + SOURCE_NSS_DB_PATH = "-source_pki_security_database_path"; + + private static final String + SOURCE_NSS_DB_DESCRIPTION = " "; + + private static final String + SOURCE_NSS_DB_PATH_EXAMPLE = SOURCE_NSS_DB_PATH + + " " + + "/export/pki"; + + private static final String + SOURCE_STORAGE_TOKEN_NAME = "-source_storage_token_name"; + + private static final String + SOURCE_STORAGE_TOKEN_DESCRIPTION = " "; + + private static final String + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE = SOURCE_STORAGE_TOKEN_NAME + + " " + + TIC + + "Internal Key Storage Token" + + TIC; + + private static final String + SOURCE_STORAGE_CERT_NICKNAME = "-source_storage_certificate_nickname"; + + private static final String + SOURCE_STORAGE_CERT_NICKNAME_DESCRIPTION = " "; + + private static final String + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE = SOURCE_STORAGE_CERT_NICKNAME + + " " + + TIC + + "storageCert cert-pki-kra" + + TIC; + + private static final String + TARGET_STORAGE_CERTIFICATE_FILE = "-target_storage_certificate_file"; + + private static final String + TARGET_STORAGE_CERTIFICATE_DESCRIPTION = " "; + + private static final String + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE = TARGET_STORAGE_CERTIFICATE_FILE + + " " + + "/export/pki/target_storage.cert"; + + private static final String + SOURCE_NSS_DB_PWDFILE = "-source_pki_security_database_pwdfile"; + + private static final String + SOURCE_NSS_DB_PWDFILE_DESCRIPTION = " "; + + private static final String + SOURCE_NSS_DB_PWDFILE_EXAMPLE = SOURCE_NSS_DB_PWDFILE + + " " + + "/export/pki/pwdfile"; + + + + // Constants: Command-line Options (ID Offset) + private static final String + APPEND_ID_OFFSET = "-append_id_offset"; + + private static final String + APPEND_ID_OFFSET_DESCRIPTION = " "; + + private static final String + APPEND_ID_OFFSET_EXAMPLE = APPEND_ID_OFFSET + + " " + + "100000000000"; + + private static final String + REMOVE_ID_OFFSET = "-remove_id_offset"; + + private static final String + REMOVE_ID_OFFSET_DESCRIPTION = " "; + + private static final String + REMOVE_ID_OFFSET_EXAMPLE = REMOVE_ID_OFFSET + + " " + + "100000000000"; + + + // Constants: Command-line Options + private static final String + SOURCE_DRM_NAMING_CONTEXT = "-source_drm_naming_context"; + + private static final String + SOURCE_DRM_NAMING_CONTEXT_DESCRIPTION = " "; + + private static final String + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE = SOURCE_DRM_NAMING_CONTEXT + + " " + + TIC + + "alpha.example.com-pki-kra" + + TIC; + + private static final String + TARGET_DRM_NAMING_CONTEXT = "-target_drm_naming_context"; + + private static final String + TARGET_DRM_NAMING_CONTEXT_DESCRIPTION = " "; + + private static final String + TARGET_DRM_NAMING_CONTEXT_EXAMPLE = TARGET_DRM_NAMING_CONTEXT + + " " + + TIC + + "omega.example.com-pki-kra" + + TIC; + + private static final String + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY = + "-process_requests_and_key_records_only"; + + + // Constants: DRMTOOL Config File private static final String DRMTOOL_CFG_PREFIX = "drmtool.ldif"; private static final String DRMTOOL_CFG_ENROLLMENT = "caEnrollmentRequest"; private static final String DRMTOOL_CFG_CA_KEY_RECORD = "caKeyRecord"; @@ -667,100 +745,235 @@ public class DRMTool { private static final String DRMTOOL_CFG_TPS_KEY_RECORD = "tpsKeyRecord"; private static final String DRMTOOL_CFG_KEYGEN = "tpsNetkeyKeygenRequest"; - // Constants: DRMTOOL Config File (DRM CA Enrollment Request Fields) - private static final String DRMTOOL_CFG_ENROLLMENT_CN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "cn"; - private static final String DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "dateOfModify"; - private static final String DRMTOOL_CFG_ENROLLMENT_DN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "dn"; - private static final String DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "extdata.keyRecord"; - private static final String DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "extdata.requestNotes"; - private static final String DRMTOOL_CFG_ENROLLMENT_REQUEST_ID = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "requestId"; - - // Constants: DRMTOOL Config File (DRM CA Key Record Fields) - private static final String DRMTOOL_CFG_CA_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_CA_KEY_RECORD + DOT + "cn"; - private static final String DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_CA_KEY_RECORD + DOT + "dateOfModify"; - private static final String DRMTOOL_CFG_CA_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_ENROLLMENT + DOT + "dn"; - private static final String DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_CA_KEY_RECORD + DOT + "privateKeyData"; - private static final String DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_CA_KEY_RECORD + DOT + "serialno"; - - // Constants: DRMTOOL Config File (DRM CA / TPS Recovery Request Fields) - private static final String DRMTOOL_CFG_RECOVERY_CN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "cn"; - private static final String DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "dateOfModify"; - private static final String DRMTOOL_CFG_RECOVERY_DN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "dn"; - private static final String DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "extdata.requestId"; - private static final String DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "extdata.requestNotes"; - private static final String DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "extdata.serialnumber"; - private static final String DRMTOOL_CFG_RECOVERY_REQUEST_ID = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_RECOVERY + DOT + "requestId"; - - // Constants: DRMTOOL Config File (DRM TPS Key Record Fields) - private static final String DRMTOOL_CFG_TPS_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_TPS_KEY_RECORD + DOT + "cn"; - private static final String DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_TPS_KEY_RECORD + DOT + "dateOfModify"; - private static final String DRMTOOL_CFG_TPS_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_TPS_KEY_RECORD + DOT + "dn"; - private static final String DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_TPS_KEY_RECORD + DOT + "privateKeyData"; - private static final String DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_TPS_KEY_RECORD + DOT + "serialno"; - - // Constants: DRMTOOL Config File (DRM TPS Netkey Keygen Request Fields) - private static final String DRMTOOL_CFG_KEYGEN_CN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "cn"; - private static final String DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "dateOfModify"; - private static final String DRMTOOL_CFG_KEYGEN_DN = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "dn"; - private static final String DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "extdata.keyRecord"; - private static final String DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "extdata.requestId"; - private static final String DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "extdata.requestNotes"; - private static final String DRMTOOL_CFG_KEYGEN_REQUEST_ID = DRMTOOL_CFG_PREFIX - + DOT + DRMTOOL_CFG_KEYGEN + DOT + "requestId"; - - // Constants: Target Certificate Information + + // Constants: DRMTOOL Config File (DRM CA Enrollment Request Fields) + private static final String + DRMTOOL_CFG_ENROLLMENT_CN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "cn"; + private static final String + DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "dateOfModify"; + private static final String + DRMTOOL_CFG_ENROLLMENT_DN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "dn"; + private static final String + DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "extdata.keyRecord"; + private static final String + DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "extdata.requestNotes"; + private static final String + DRMTOOL_CFG_ENROLLMENT_REQUEST_ID = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "requestId"; + + + // Constants: DRMTOOL Config File (DRM CA Key Record Fields) + private static final String + DRMTOOL_CFG_CA_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_CA_KEY_RECORD + + DOT + + "cn"; + private static final String + DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_CA_KEY_RECORD + + DOT + + "dateOfModify"; + private static final String + DRMTOOL_CFG_CA_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_ENROLLMENT + + DOT + + "dn"; + private static final String + DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_CA_KEY_RECORD + + DOT + + "privateKeyData"; + private static final String + DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_CA_KEY_RECORD + + DOT + + "serialno"; + + + // Constants: DRMTOOL Config File (DRM CA / TPS Recovery Request Fields) + private static final String + DRMTOOL_CFG_RECOVERY_CN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "cn"; + private static final String + DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "dateOfModify"; + private static final String + DRMTOOL_CFG_RECOVERY_DN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "dn"; + private static final String + DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "extdata.requestId"; + private static final String + DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "extdata.requestNotes"; + private static final String + DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "extdata.serialnumber"; + private static final String + DRMTOOL_CFG_RECOVERY_REQUEST_ID = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_RECOVERY + + DOT + + "requestId"; + + + // Constants: DRMTOOL Config File (DRM TPS Key Record Fields) + private static final String + DRMTOOL_CFG_TPS_KEY_RECORD_CN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_TPS_KEY_RECORD + + DOT + + "cn"; + private static final String + DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_TPS_KEY_RECORD + + DOT + + "dateOfModify"; + private static final String + DRMTOOL_CFG_TPS_KEY_RECORD_DN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_TPS_KEY_RECORD + + DOT + + "dn"; + private static final String + DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_TPS_KEY_RECORD + + DOT + + "privateKeyData"; + private static final String + DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_TPS_KEY_RECORD + + DOT + + "serialno"; + + + // Constants: DRMTOOL Config File (DRM TPS Netkey Keygen Request Fields) + private static final String + DRMTOOL_CFG_KEYGEN_CN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "cn"; + private static final String + DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "dateOfModify"; + private static final String + DRMTOOL_CFG_KEYGEN_DN = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "dn"; + private static final String + DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "extdata.keyRecord"; + private static final String + DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "extdata.requestId"; + private static final String + DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "extdata.requestNotes"; + private static final String + DRMTOOL_CFG_KEYGEN_REQUEST_ID = DRMTOOL_CFG_PREFIX + + DOT + + DRMTOOL_CFG_KEYGEN + + DOT + + "requestId"; + + + // Constants: Target Certificate Information private static final String HEADER = "-----BEGIN"; private static final String TRAILER = "-----END"; private static final String X509_INFO = "x509.INFO"; - // Constants: DRM LDIF Record Fields + + // Constants: DRM LDIF Record Fields private static final String DRM_LDIF_ARCHIVED_BY = "archivedBy:"; private static final String DRM_LDIF_CN = "cn:"; private static final String DRM_LDIF_DATE_OF_MODIFY = "dateOfModify:"; private static final String DRM_LDIF_DN = "dn:"; private static final String DRM_LDIF_DN_EMBEDDED_CN_DATA = "dn: cn"; - private static final String DRM_LDIF_EXTDATA_AUTH_TOKEN_USER = "extdata-auth--005ftoken;user:"; - private static final String DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN = "extdata-auth--005ftoken;userdn:"; - private static final String DRM_LDIF_EXTDATA_KEY_RECORD = "extdata-keyrecord:"; - private static final String DRM_LDIF_EXTDATA_REQUEST_ID = "extdata-requestid:"; - private static final String DRM_LDIF_EXTDATA_REQUEST_NOTES = "extdata-requestnotes:"; - private static final String DRM_LDIF_EXTDATA_REQUEST_TYPE = "extdata-requesttype:"; - private static final String DRM_LDIF_EXTDATA_SERIAL_NUMBER = "extdata-serialnumber:"; + private static final String + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER = "extdata-auth--005ftoken;user:"; + private static final String + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN = "extdata-auth--005ftoken;userdn:"; + private static final String + DRM_LDIF_EXTDATA_KEY_RECORD = "extdata-keyrecord:"; + private static final String + DRM_LDIF_EXTDATA_REQUEST_ID = "extdata-requestid:"; + private static final String + DRM_LDIF_EXTDATA_REQUEST_NOTES = "extdata-requestnotes:"; + private static final String + DRM_LDIF_EXTDATA_REQUEST_TYPE = "extdata-requesttype:"; + private static final String + DRM_LDIF_EXTDATA_SERIAL_NUMBER = "extdata-serialnumber:"; private static final String DRM_LDIF_PRIVATE_KEY_DATA = "privateKeyData::"; private static final String DRM_LDIF_REQUEST_ID = "requestId:"; private static final String DRM_LDIF_REQUEST_TYPE = "requestType:"; private static final String DRM_LDIF_SERIAL_NO = "serialno:"; - // Constants: DRM LDIF Record Values + + // Constants: DRM LDIF Record Values private static final int INITIAL_LDIF_RECORD_CAPACITY = 0; private static final int EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH = 56; private static final int PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH = 60; @@ -771,26 +984,41 @@ public class DRMTool { private static final String DRM_LDIF_RECOVERY = "recovery"; private static final String DRM_LDIF_TPS_KEY_RECORD = "TPS"; - // Constants: DRM LDIF Record Messages + + // Constants: DRM LDIF Record Messages private static final String DRM_LDIF_REWRAP_MESSAGE = "REWRAPPED the '" - + "existing DES3 " + "symmetric " + "session key" + "' with the '"; + + "existing DES3 " + + "symmetric " + + "session key" + + "' with the '"; private static final String DRM_LDIF_RSA_MESSAGE = "-bit RSA public key' " - + "obtained from the " + "target storage " + "certificate"; - private static final String DRM_LDIF_USED_PWDFILE_MESSAGE = "USED source PKI security database " - + "password file"; - private static final String DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE = "APPENDED ID offset"; - private static final String DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE = "REMOVED ID offset"; - private static final String DRM_LDIF_SOURCE_NAME_CONTEXT_MESSAGE = "RENAMED source DRM naming context '"; - private static final String DRM_LDIF_TARGET_NAME_CONTEXT_MESSAGE = "' to target DRM naming context '"; - private static final String DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE = "PROCESSED requests and key records ONLY!"; + + "obtained from the " + + "target storage " + + "certificate"; + private static final String DRM_LDIF_USED_PWDFILE_MESSAGE = + "USED source PKI security database " + + "password file"; + private static final String DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE = + "APPENDED ID offset"; + private static final String DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE = + "REMOVED ID offset"; + private static final String DRM_LDIF_SOURCE_NAME_CONTEXT_MESSAGE = + "RENAMED source DRM naming context '"; + private static final String DRM_LDIF_TARGET_NAME_CONTEXT_MESSAGE = + "' to target DRM naming context '"; + private static final String + DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE = + "PROCESSED requests and key records ONLY!"; + /*************/ /* Variables */ /*************/ - // Variables: Calendar + // Variables: Calendar private static String mDateOfModify = null; + // Variables: Command-Line Options private static boolean mMandatoryFlag = false; private static boolean mRewrapFlag = false; @@ -806,12 +1034,14 @@ public class DRMTool { private static int mRemoveIdOffsetNameValuePairs = 0; private static int mDrmNamingContextNameValuePairs = 0; + // Variables: Command-Line Values (Mandatory) private static String mDrmtoolCfgFilename = null; private static String mSourceLdifFilename = null; private static String mTargetLdifFilename = null; private static String mLogFilename = null; + // Variables: Command-Line Values (Rewrap) private static String mSourcePKISecurityDatabasePath = null; private static String mSourceStorageTokenName = null; @@ -825,34 +1055,41 @@ public class DRMTool { private static BigInteger mAppendIdOffset = null; private static BigInteger mRemoveIdOffset = null; + // Variables: Command-Line Values (DRM Naming Contexts) private static String mSourceDrmNamingContext = null; private static String mTargetDrmNamingContext = null; - // Variables: DRMTOOL Config File Parameters of Interest + + // Variables: DRMTOOL Config File Parameters of Interest private static Hashtable drmtoolCfg = null; - // Variables: DRMTOOL LDIF File Parameters of Interest + + // Variables: DRMTOOL LDIF File Parameters of Interest private static Vector record = null; private static Iterator ldif_record = null; - // Variables: Logging - private static boolean mDebug = false; // set 'true' for debug messages + + // Variables: Logging + private static boolean mDebug = false; // set 'true' for debug messages private static PrintWriter logger = null; private static String current_date_and_time = null; - // Variables: PKCS #11 Information + + // Variables: PKCS #11 Information private static CryptoToken mSourceToken = null; private static X509Certificate mUnwrapCert = null; private static PrivateKey mUnwrapPrivateKey = null; private static PublicKey mWrapPublicKey = null; private static int mPublicKeySize = 0; - // Variables: DRM LDIF Record Messages + + // Variables: DRM LDIF Record Messages private static String mSourcePKISecurityDatabasePwdfileMessage = null; private static String mDrmNamingContextMessage = null; private static String mProcessRequestsAndKeyRecordsOnlyMessage = null; + /********************/ /* Calendar Methods */ /********************/ @@ -860,124 +1097,330 @@ public class DRMTool { /** * This method is used to get the current date and time. *

- * + * * @param pattern string containing desired format of date and time * @return a formatted string containing the current date and time */ - private static String now(String pattern) { + private static String now( String pattern ) { Calendar cal = Calendar.getInstance(); - SimpleDateFormat sdf = new SimpleDateFormat(pattern); - return sdf.format(cal.getTime()); + SimpleDateFormat sdf = new SimpleDateFormat( pattern ); + return sdf.format( cal.getTime() ); } + /*****************/ /* Usage Methods */ /*****************/ /** - * This method prints out the proper command-line usage required to execute - * DRMTool. + * This method prints out the proper command-line usage required to + * execute DRMTool. */ private static void printUsage() { - System.out.println("Usage: " + DRM_TOOL + NEWLINE + " " - + DRMTOOL_CFG_FILE + NEWLINE + " " - + DRMTOOL_CFG_DESCRIPTION + NEWLINE + " " - + SOURCE_LDIF_FILE + NEWLINE + " " - + SOURCE_LDIF_DESCRIPTION + NEWLINE + " " - + TARGET_LDIF_FILE + NEWLINE + " " - + TARGET_LDIF_DESCRIPTION + NEWLINE + " " + LOG_FILE - + NEWLINE + " " + LOG_DESCRIPTION + NEWLINE + " " - + "[" + SOURCE_NSS_DB_PATH + NEWLINE + " " - + SOURCE_NSS_DB_DESCRIPTION + "]" + NEWLINE + " " + "[" - + SOURCE_STORAGE_TOKEN_NAME + NEWLINE + " " - + SOURCE_STORAGE_TOKEN_DESCRIPTION + "]" + NEWLINE + " " - + "[" + SOURCE_STORAGE_CERT_NICKNAME + NEWLINE + " " - + SOURCE_STORAGE_CERT_NICKNAME_DESCRIPTION + "]" + NEWLINE - + " " + "[" + TARGET_STORAGE_CERTIFICATE_FILE + NEWLINE - + " " + TARGET_STORAGE_CERTIFICATE_DESCRIPTION + "]" - + NEWLINE + " " + "[" + SOURCE_NSS_DB_PWDFILE + NEWLINE - + " " + SOURCE_NSS_DB_PWDFILE_DESCRIPTION + "]" - + NEWLINE + " " + "[" + APPEND_ID_OFFSET + NEWLINE - + " " + APPEND_ID_OFFSET_DESCRIPTION + "]" + NEWLINE - + " " + "[" + REMOVE_ID_OFFSET + NEWLINE + " " - + REMOVE_ID_OFFSET_DESCRIPTION + "]" + NEWLINE + " " - + "[" + SOURCE_DRM_NAMING_CONTEXT + NEWLINE + " " - + SOURCE_DRM_NAMING_CONTEXT_DESCRIPTION + "]" + NEWLINE - + " " + "[" + TARGET_DRM_NAMING_CONTEXT + NEWLINE - + " " + TARGET_DRM_NAMING_CONTEXT_DESCRIPTION + "]" - + NEWLINE + " " + "[" - + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + "]" + NEWLINE); - - System.out.println("Example of 'Rewrap and Append ID Offset':" - + NEWLINE + NEWLINE + " " + DRM_TOOL + NEWLINE - + " " + DRMTOOL_CFG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_LDIF_FILE_EXAMPLE + NEWLINE + " " - + TARGET_LDIF_FILE_EXAMPLE + NEWLINE + " " - + LOG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_NSS_DB_PATH_EXAMPLE + NEWLINE + " " - + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE + NEWLINE + " " - + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE + NEWLINE + " " - + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE + NEWLINE - + " " + SOURCE_NSS_DB_PWDFILE_EXAMPLE + NEWLINE - + " " + APPEND_ID_OFFSET_EXAMPLE + NEWLINE + " " - + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + NEWLINE); - - System.out.println("Example of 'Rewrap and Remove ID Offset':" - + NEWLINE + NEWLINE + " " + DRM_TOOL + NEWLINE - + " " + DRMTOOL_CFG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_LDIF_FILE_EXAMPLE + NEWLINE + " " - + TARGET_LDIF_FILE_EXAMPLE + NEWLINE + " " - + LOG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_NSS_DB_PATH_EXAMPLE + NEWLINE + " " - + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE + NEWLINE + " " - + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE + NEWLINE + " " - + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE + NEWLINE - + " " + SOURCE_NSS_DB_PWDFILE_EXAMPLE + NEWLINE - + " " + REMOVE_ID_OFFSET_EXAMPLE + NEWLINE + " " - + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + NEWLINE); - - System.out.println("Example of 'Rewrap':" + NEWLINE + NEWLINE - + " " + DRM_TOOL + NEWLINE + " " - + DRMTOOL_CFG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_LDIF_FILE_EXAMPLE + NEWLINE + " " - + TARGET_LDIF_FILE_EXAMPLE + NEWLINE + " " - + LOG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_NSS_DB_PATH_EXAMPLE + NEWLINE + " " - + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE + NEWLINE + " " - + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE + NEWLINE + " " - + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE + NEWLINE - + " " + SOURCE_NSS_DB_PWDFILE_EXAMPLE + NEWLINE - + " " + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE - + " " + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE - + " " + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + NEWLINE); - - System.out.println("Example of 'Append ID Offset':" + NEWLINE + NEWLINE - + " " + DRM_TOOL + NEWLINE + " " - + DRMTOOL_CFG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_LDIF_FILE_EXAMPLE + NEWLINE + " " - + TARGET_LDIF_FILE_EXAMPLE + NEWLINE + " " - + LOG_FILE_EXAMPLE + NEWLINE + " " - + APPEND_ID_OFFSET_EXAMPLE + NEWLINE + " " - + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + NEWLINE); - - System.out.println("Example of 'Remove ID Offset':" + NEWLINE + NEWLINE - + " " + DRM_TOOL + NEWLINE + " " - + DRMTOOL_CFG_FILE_EXAMPLE + NEWLINE + " " - + SOURCE_LDIF_FILE_EXAMPLE + NEWLINE + " " - + TARGET_LDIF_FILE_EXAMPLE + NEWLINE + " " - + LOG_FILE_EXAMPLE + NEWLINE + " " - + REMOVE_ID_OFFSET_EXAMPLE + NEWLINE + " " - + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + NEWLINE + " " - + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + NEWLINE); + System.out.println( "Usage: " + + DRM_TOOL + + NEWLINE + + " " + + DRMTOOL_CFG_FILE + + NEWLINE + + " " + + DRMTOOL_CFG_DESCRIPTION + + NEWLINE + + " " + + SOURCE_LDIF_FILE + + NEWLINE + + " " + + SOURCE_LDIF_DESCRIPTION + + NEWLINE + + " " + + TARGET_LDIF_FILE + + NEWLINE + + " " + + TARGET_LDIF_DESCRIPTION + + NEWLINE + + " " + + LOG_FILE + + NEWLINE + + " " + + LOG_DESCRIPTION + + NEWLINE + + " " + + "[" + + SOURCE_NSS_DB_PATH + + NEWLINE + + " " + + SOURCE_NSS_DB_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + SOURCE_STORAGE_TOKEN_NAME + + NEWLINE + + " " + + SOURCE_STORAGE_TOKEN_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + SOURCE_STORAGE_CERT_NICKNAME + + NEWLINE + + " " + + SOURCE_STORAGE_CERT_NICKNAME_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + TARGET_STORAGE_CERTIFICATE_FILE + + NEWLINE + + " " + + TARGET_STORAGE_CERTIFICATE_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + SOURCE_NSS_DB_PWDFILE + + NEWLINE + + " " + + SOURCE_NSS_DB_PWDFILE_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + APPEND_ID_OFFSET + + NEWLINE + + " " + + APPEND_ID_OFFSET_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + REMOVE_ID_OFFSET + + NEWLINE + + " " + + REMOVE_ID_OFFSET_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + SOURCE_DRM_NAMING_CONTEXT + + NEWLINE + + " " + + SOURCE_DRM_NAMING_CONTEXT_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + TARGET_DRM_NAMING_CONTEXT + + NEWLINE + + " " + + TARGET_DRM_NAMING_CONTEXT_DESCRIPTION + + "]" + + NEWLINE + + " " + + "[" + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + + "]" + + NEWLINE ); + + System.out.println( "Example of 'Rewrap and Append ID Offset':" + + NEWLINE + + NEWLINE + + " " + + DRM_TOOL + + NEWLINE + + " " + + DRMTOOL_CFG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + TARGET_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + LOG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_NSS_DB_PATH_EXAMPLE + + NEWLINE + + " " + + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE + + NEWLINE + + " " + + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE + + NEWLINE + + " " + + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_NSS_DB_PWDFILE_EXAMPLE + + NEWLINE + + " " + + APPEND_ID_OFFSET_EXAMPLE + + NEWLINE + + " " + + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + + NEWLINE ); + + System.out.println( "Example of 'Rewrap and Remove ID Offset':" + + NEWLINE + + NEWLINE + + " " + + DRM_TOOL + + NEWLINE + + " " + + DRMTOOL_CFG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + TARGET_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + LOG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_NSS_DB_PATH_EXAMPLE + + NEWLINE + + " " + + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE + + NEWLINE + + " " + + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE + + NEWLINE + + " " + + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_NSS_DB_PWDFILE_EXAMPLE + + NEWLINE + + " " + + REMOVE_ID_OFFSET_EXAMPLE + + NEWLINE + + " " + + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + + NEWLINE ); + + System.out.println( "Example of 'Rewrap':" + + NEWLINE + + NEWLINE + + " " + + DRM_TOOL + + NEWLINE + + " " + + DRMTOOL_CFG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + TARGET_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + LOG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_NSS_DB_PATH_EXAMPLE + + NEWLINE + + " " + + SOURCE_STORAGE_TOKEN_NAME_EXAMPLE + + NEWLINE + + " " + + SOURCE_STORAGE_CERT_NICKNAME_EXAMPLE + + NEWLINE + + " " + + TARGET_STORAGE_CERTIFICATE_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_NSS_DB_PWDFILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + + NEWLINE ); + + System.out.println( "Example of 'Append ID Offset':" + + NEWLINE + + NEWLINE + + " " + + DRM_TOOL + + NEWLINE + + " " + + DRMTOOL_CFG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + TARGET_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + LOG_FILE_EXAMPLE + + NEWLINE + + " " + + APPEND_ID_OFFSET_EXAMPLE + + NEWLINE + + " " + + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + + NEWLINE ); + + System.out.println( "Example of 'Remove ID Offset':" + + NEWLINE + + NEWLINE + + " " + + DRM_TOOL + + NEWLINE + + " " + + DRMTOOL_CFG_FILE_EXAMPLE + + NEWLINE + + " " + + SOURCE_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + TARGET_LDIF_FILE_EXAMPLE + + NEWLINE + + " " + + LOG_FILE_EXAMPLE + + NEWLINE + + " " + + REMOVE_ID_OFFSET_EXAMPLE + + NEWLINE + + " " + + SOURCE_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + TARGET_DRM_NAMING_CONTEXT_EXAMPLE + + NEWLINE + + " " + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY + + NEWLINE ); } + /*******************/ /* Logging Methods */ /*******************/ @@ -985,72 +1428,83 @@ public class DRMTool { /** * This method opens a new log file for writing. *

- * + * * @param logfile string containing the name of the log file to be opened */ - private static void open_log(String logfile) { + private static void open_log( String logfile ) { try { logger = new PrintWriter( - new BufferedWriter(new FileWriter(logfile))); - } catch (IOException eFile) { - System.err.println("ERROR: Unable to open file '" + logfile - + "' for writing: '" + eFile.toString() + "'" + NEWLINE); - System.exit(0); + new BufferedWriter( + new FileWriter( logfile ) ) ); + } catch( IOException eFile ) { + System.err.println( "ERROR: Unable to open file '" + + logfile + + "' for writing: '" + + eFile.toString() + + "'" + + NEWLINE ); + System.exit( 0 ); } } + /** * This method closes the specified log file. *

- * + * * @param logfile string containing the name of the log file to be closed */ - private static void close_log(String logfile) { + private static void close_log( String logfile ) { logger.close(); } + /** - * This method writes the specified message to the log file, and also to - * 'stderr' if the boolean flag is set to 'true'. + * This method writes the specified message to the log file, and also + * to 'stderr' if the boolean flag is set to 'true'. *

- * + * * @param msg string containing the message to be written to the log file * @param stderr boolean which also writes the message to 'stderr' if 'true' */ - private static void log(String msg, boolean stderr) { - current_date_and_time = now(LOGGING_DATE_PATTERN); - if (stderr) { - System.err.println(msg); + private static void log( String msg, boolean stderr ) { + current_date_and_time = now( LOGGING_DATE_PATTERN ); + if( stderr ) { + System.err.println( msg ); } - logger.write("[" + current_date_and_time + "]: " + msg); + logger.write( "[" + + current_date_and_time + + "]: " + + msg ); logger.flush(); } + /*********************************************/ - /* PKCS #11: Rewrap RSA Storage Key Methods */ + /* PKCS #11: Rewrap RSA Storage Key Methods */ /*********************************************/ /** * Helper method to determine if two arrays contain the same values. - * + * * This method is based upon code from 'com.netscape.kra.StorageKeyUnit'. *

- * + * * @param bytes first array of bytes * @param ints second array of bytes * @return true if the two arrays are identical */ - private static boolean arraysEqual(byte[] bytes, byte[] ints) { - if (bytes == null || ints == null) { + private static boolean arraysEqual( byte[] bytes, byte[] ints ) { + if( bytes == null || ints == null ) { return false; } - if (bytes.length != ints.length) { + if( bytes.length != ints.length ) { return false; } - for (int i = 0; i < bytes.length; i++) { - if (bytes[i] != ints[i]) { + for( int i = 0; i < bytes.length; i++ ) { + if( bytes[i] != ints[i] ) { return false; } } @@ -1058,43 +1512,49 @@ public class DRMTool { return true; } + /** - * This method is used to obtain the private RSA storage key from the - * "source" DRM instance's security databases. - * + * This method is used to obtain the private RSA storage key from + * the "source" DRM instance's security databases. + * * This method is based upon code from 'com.netscape.kra.StorageKeyUnit'. *

- * + * * @return the private RSA storage key from the "source" DRM */ private static PrivateKey getPrivateKey() { try { - PrivateKey pk[] = mSourceToken.getCryptoStore().getPrivateKeys(); - - for (int i = 0; i < pk.length; i++) { - if (arraysEqual(pk[i].getUniqueID(), - ((TokenCertificate) mUnwrapCert).getUniqueID())) { - return pk[i]; - } - } - } catch (TokenException exToken) { - log("ERROR: Getting private key - " + "TokenException: '" - + exToken.toString() + "'" + NEWLINE, true); - System.exit(0); + PrivateKey pk[] = mSourceToken.getCryptoStore().getPrivateKeys(); + + for( int i = 0; i < pk.length; i++ ) { + if( arraysEqual( pk[i].getUniqueID(), + ( ( TokenCertificate ) + mUnwrapCert ).getUniqueID() ) ) { + return pk[i]; + } + } + } catch( TokenException exToken ) { + log( "ERROR: Getting private key - " + + "TokenException: '" + + exToken.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } return null; } + /** - * This method gets the public key from the certificate stored in the - * "target" DRM storage certificate file. It also obtains the keysize of - * this RSA key. - * + * This method gets the public key from the certificate stored + * in the "target" DRM storage certificate file. It also obtains + * the keysize of this RSA key. + * * This method is based upon code from * 'com.netscape.cmstools.PrettyPrintCert'. *

- * + * * @return the public RSA storage key from the "target" DRM */ private static PublicKey getPublicKey() { @@ -1110,15 +1570,21 @@ public class DRMTool { // encoded certificate contained within the file // specified on the command line try { - inputCert = new BufferedReader(new InputStreamReader( - new BufferedInputStream(new FileInputStream( - mTargetStorageCertificateFilename)))); - } catch (FileNotFoundException exWrapFileNotFound) { - log("ERROR: No target storage " + "certificate file named '" - + mTargetStorageCertificateFilename - + "' exists! FileNotFoundException: '" - + exWrapFileNotFound.toString() + "'" + NEWLINE, true); - System.exit(0); + inputCert = new BufferedReader( + new InputStreamReader( + new BufferedInputStream( + new FileInputStream( + mTargetStorageCertificateFilename + ) ) ) ); + } catch( FileNotFoundException exWrapFileNotFound ) { + log( "ERROR: No target storage " + + "certificate file named '" + + mTargetStorageCertificateFilename + + "' exists! FileNotFoundException: '" + + exWrapFileNotFound.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Read the entire contents of the specified BASE 64 encoded @@ -1126,64 +1592,78 @@ public class DRMTool { // headers beginning with HEADER and any trailers beginning // with TRAILER try { - while ((encodedBASE64CertChunk = inputCert.readLine()) != null) { - if (!(encodedBASE64CertChunk.startsWith(HEADER)) - && !(encodedBASE64CertChunk.startsWith(TRAILER))) { + while( ( encodedBASE64CertChunk = inputCert.readLine() ) != null ) { + if( !( encodedBASE64CertChunk.startsWith( HEADER ) ) && + !( encodedBASE64CertChunk.startsWith( TRAILER ) ) ) { encodedBASE64Cert += encodedBASE64CertChunk.trim(); } } - } catch (IOException exWrapReadLineIO) { - log("ERROR: Unexpected BASE64 " - + "encoded error encountered while reading '" - + mTargetStorageCertificateFilename + "'! IOException: '" - + exWrapReadLineIO.toString() + "'" + NEWLINE, true); - System.exit(0); + } catch( IOException exWrapReadLineIO ) { + log( "ERROR: Unexpected BASE64 " + + "encoded error encountered while reading '" + + mTargetStorageCertificateFilename + + "'! IOException: '" + + exWrapReadLineIO.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Close the DataInputStream() object try { inputCert.close(); - } catch (IOException exWrapCloseIO) { - log("ERROR: Unexpected BASE64 " - + "encoded error encountered in closing '" - + mTargetStorageCertificateFilename + "'! IOException: '" - + exWrapCloseIO.toString() + "'" + NEWLINE, true); - System.exit(0); + } catch( IOException exWrapCloseIO ) { + log( "ERROR: Unexpected BASE64 " + + "encoded error encountered in closing '" + + mTargetStorageCertificateFilename + + "'! IOException: '" + + exWrapCloseIO.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Decode the ASCII BASE 64 certificate enclosed in the // String() object into a BINARY BASE 64 byte[] object - decodedBASE64Cert = com.netscape.osutil.OSUtil.AtoB(encodedBASE64Cert); + decodedBASE64Cert = com.netscape.osutil.OSUtil.AtoB( + encodedBASE64Cert ); // Create an X509CertImpl() object from // the BINARY BASE 64 byte[] object try { - cert = new X509CertImpl(decodedBASE64Cert); - } catch (CertificateException exWrapCertificate) { - log("ERROR: Error encountered " + "in parsing certificate in '" - + mTargetStorageCertificateFilename - + "' CertificateException: '" - + exWrapCertificate.toString() + "'" + NEWLINE, true); - System.exit(0); + cert = new X509CertImpl( decodedBASE64Cert ); + } catch( CertificateException exWrapCertificate ) { + log( "ERROR: Error encountered " + + "in parsing certificate in '" + + mTargetStorageCertificateFilename + + "' CertificateException: '" + + exWrapCertificate.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Extract the Public Key key = cert.getPublicKey(); - if (key == null) { - log("ERROR: Unable to extract public key " - + "from certificate that was stored in '" - + mTargetStorageCertificateFilename + "'." + NEWLINE, true); - System.exit(0); + if( key == null ) { + log( "ERROR: Unable to extract public key " + + "from certificate that was stored in '" + + mTargetStorageCertificateFilename + + "'." + + NEWLINE, true ); + System.exit( 0 ); } // Convert this X.509 public key --> RSA public key try { - rsakey = new RSAPublicKey(key.getEncoded()); - } catch (InvalidKeyException exInvalidKey) { - log("ERROR: Converting X.509 public key --> RSA public key - " - + "InvalidKeyException: '" + exInvalidKey.toString() + "'" - + NEWLINE, true); - System.exit(0); + rsakey = new RSAPublicKey( key.getEncoded() ); + } catch( InvalidKeyException exInvalidKey ) { + log( "ERROR: Converting X.509 public key --> RSA public key - " + + "InvalidKeyException: '" + + exInvalidKey.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Obtain the Public Key's keysize @@ -1192,12 +1672,14 @@ public class DRMTool { return key; } + /** - * This method is used to obtain the private RSA storage key from the - * "source" DRM instance's security databases and the public RSA storage key - * from the certificate stored in the "target" DRM storage certificate file. + * This method is used to obtain the private RSA storage key + * from the "source" DRM instance's security databases and + * the public RSA storage key from the certificate stored in + * the "target" DRM storage certificate file. *

- * + * * @return true if successfully able to obtain both keys */ private static boolean obtain_RSA_rewrapping_keys() { @@ -1205,191 +1687,245 @@ public class DRMTool { // Initialize the source security databases try { - log("Initializing source PKI security databases in '" - + mSourcePKISecurityDatabasePath + "'." + NEWLINE, true); - - CryptoManager.initialize(mSourcePKISecurityDatabasePath); - } catch (KeyDatabaseException exKey) { - log("ERROR: source_pki_security_database_path='" - + mSourcePKISecurityDatabasePath - + "' KeyDatabaseException: '" + exKey.toString() + "'" - + NEWLINE, true); - System.exit(0); - } catch (CertDatabaseException exCert) { - log("ERROR: source_pki_security_database_path='" - + mSourcePKISecurityDatabasePath - + "' CertDatabaseException: '" + exCert.toString() + "'" - + NEWLINE, true); - System.exit(0); - } catch (AlreadyInitializedException exAlreadyInitialized) { - log("ERROR: source_pki_security_database_path='" - + mSourcePKISecurityDatabasePath - + "' AlreadyInitializedException: '" - + exAlreadyInitialized.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (GeneralSecurityException exSecurity) { - log("ERROR: source_pki_security_database_path='" - + mSourcePKISecurityDatabasePath - + "' GeneralSecurityException: '" + exSecurity.toString() - + "'" + NEWLINE, true); - System.exit(0); + log( "Initializing source PKI security databases in '" + + mSourcePKISecurityDatabasePath + "'." + + NEWLINE, true ); + + CryptoManager.initialize( mSourcePKISecurityDatabasePath ); + } catch( KeyDatabaseException exKey ) { + log( "ERROR: source_pki_security_database_path='" + + mSourcePKISecurityDatabasePath + + "' KeyDatabaseException: '" + + exKey.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( CertDatabaseException exCert ) { + log( "ERROR: source_pki_security_database_path='" + + mSourcePKISecurityDatabasePath + + "' CertDatabaseException: '" + + exCert.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( AlreadyInitializedException exAlreadyInitialized ) { + log( "ERROR: source_pki_security_database_path='" + + mSourcePKISecurityDatabasePath + + "' AlreadyInitializedException: '" + + exAlreadyInitialized.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( GeneralSecurityException exSecurity ) { + log( "ERROR: source_pki_security_database_path='" + + mSourcePKISecurityDatabasePath + + "' GeneralSecurityException: '" + + exSecurity.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Retrieve the source storage token by its name try { - log("Retrieving token from CryptoManager." + NEWLINE, true); + log( "Retrieving token from CryptoManager." + + NEWLINE, true ); cm = CryptoManager.getInstance(); - log("Retrieving source storage token called '" - + mSourceStorageTokenName + "'." + NEWLINE, true); + log( "Retrieving source storage token called '" + + mSourceStorageTokenName + + "'." + + NEWLINE, true ); - if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) { + if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) { mSourceToken = cm.getInternalKeyStorageToken(); } else { - mSourceToken = cm.getTokenByName(mSourceStorageTokenName); + mSourceToken = cm.getTokenByName( mSourceStorageTokenName ); } - if (mSourceToken == null) { + if( mSourceToken == null ) { return FAILURE; } - if (mPwdfileFlag) { + if( mPwdfileFlag ) { BufferedReader in = null; String pwd = null; Password mPwd = null; try { - in = new BufferedReader(new FileReader( - mSourcePKISecurityDatabasePwdfile)); + in = new BufferedReader( + new FileReader( + mSourcePKISecurityDatabasePwdfile ) ); pwd = in.readLine(); - mPwd = new Password(pwd.toCharArray()); - - mSourceToken.login(mPwd); - } catch (Exception exReadPwd) { - log("ERROR: Failed to read the keydb password from " - + "the file '" + mSourcePKISecurityDatabasePwdfile - + "'. Exception: '" + exReadPwd.toString() + "'" - + NEWLINE, true); - System.exit(0); + mPwd = new Password( pwd.toCharArray() ); + + mSourceToken.login( mPwd ); + } catch( Exception exReadPwd ) { + log( "ERROR: Failed to read the keydb password from " + + "the file '" + + mSourcePKISecurityDatabasePwdfile + + "'. Exception: '" + + exReadPwd.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } } - } catch (Exception exUninitialized) { - log("ERROR: Uninitialized CryptoManager - '" - + exUninitialized.toString() + "'" + NEWLINE, true); - System.exit(0); + } catch( Exception exUninitialized ) { + log( "ERROR: Uninitialized CryptoManager - '" + + exUninitialized.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // Retrieve the source storage cert by its nickname try { - if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) { - log("Retrieving source storage cert with nickname of '" - + mSourceStorageCertNickname + "'." + NEWLINE, true); - - mUnwrapCert = cm.findCertByNickname(mSourceStorageCertNickname); + if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) { + log( "Retrieving source storage cert with nickname of '" + + mSourceStorageCertNickname + + "'." + + NEWLINE, true ); + + mUnwrapCert = cm.findCertByNickname( mSourceStorageCertNickname + ); } else { - log("Retrieving source storage cert with nickname of '" - + mSourceStorageTokenName + ":" - + mSourceStorageCertNickname + "'. " + NEWLINE, true); - mUnwrapCert = cm.findCertByNickname(mSourceStorageTokenName - + ":" + mSourceStorageCertNickname); + log( "Retrieving source storage cert with nickname of '" + + mSourceStorageTokenName + + ":" + + mSourceStorageCertNickname + + "'. " + + NEWLINE, true ); + mUnwrapCert = cm.findCertByNickname( mSourceStorageTokenName + + ":" + + mSourceStorageCertNickname + ); } - if (mUnwrapCert == null) { + if( mUnwrapCert == null ) { return FAILURE; } - } catch (ObjectNotFoundException exUnwrapObjectNotFound) { - if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) { - log("ERROR: No internal " + "source storage cert named '" - + mSourceStorageCertNickname - + "' exists! ObjectNotFoundException: '" - + exUnwrapObjectNotFound.toString() + "'" + NEWLINE, - true); + } catch( ObjectNotFoundException exUnwrapObjectNotFound ) { + if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) { + log( "ERROR: No internal " + + "source storage cert named '" + + mSourceStorageCertNickname + + "' exists! ObjectNotFoundException: '" + + exUnwrapObjectNotFound.toString() + + "'" + + NEWLINE, true ); } else { - log("ERROR: No " + "source storage cert named '" - + mSourceStorageTokenName + ":" - + mSourceStorageCertNickname - + "' exists! ObjectNotFoundException: '" - + exUnwrapObjectNotFound + "'" + NEWLINE, true); + log( "ERROR: No " + + "source storage cert named '" + + mSourceStorageTokenName + + ":" + + mSourceStorageCertNickname + + "' exists! ObjectNotFoundException: '" + + exUnwrapObjectNotFound + + "'" + + NEWLINE, true ); } - System.exit(0); - } catch (TokenException exUnwrapToken) { - if (mSourceStorageTokenName.equals(INTERNAL_TOKEN)) { - log("ERROR: No internal " + "source storage cert named '" - + mSourceStorageCertNickname - + "' exists! TokenException: '" - + exUnwrapToken.toString() + "'" + NEWLINE, true); + System.exit( 0 ); + } catch( TokenException exUnwrapToken ) { + if( mSourceStorageTokenName.equals( INTERNAL_TOKEN ) ) { + log( "ERROR: No internal " + + "source storage cert named '" + + mSourceStorageCertNickname + + "' exists! TokenException: '" + + exUnwrapToken.toString() + + "'" + + NEWLINE, true ); } else { - log("ERROR: No " + "source storage cert named '" - + mSourceStorageTokenName + ":" - + mSourceStorageCertNickname - + "' exists! TokenException: '" + exUnwrapToken + "'" - + NEWLINE, true); + log( "ERROR: No " + + "source storage cert named '" + + mSourceStorageTokenName + + ":" + + mSourceStorageCertNickname + + "' exists! TokenException: '" + + exUnwrapToken + + "'" + + NEWLINE, true ); } - System.exit(0); + System.exit( 0 ); } + // Extract the private key from the source storage token - log("BEGIN: Obtaining the private key from " - + "the source storage token . . ." + NEWLINE, true); + log( "BEGIN: Obtaining the private key from " + + "the source storage token . . ." + + NEWLINE, true ); mUnwrapPrivateKey = getPrivateKey(); - if (mUnwrapPrivateKey == null) { - log("ERROR: Failed extracting " - + "private key from the source storage token." + NEWLINE, - true); - System.exit(0); + if( mUnwrapPrivateKey == null ) { + log( "ERROR: Failed extracting " + + "private key from the source storage token." + + NEWLINE, true ); + System.exit( 0 ); } - log("FINISHED: Obtaining the private key from " - + "the source storage token." + NEWLINE, true); + log( "FINISHED: Obtaining the private key from " + + "the source storage token." + + NEWLINE, true ); + // Extract the public key from the target storage certificate try { - log("BEGIN: Obtaining the public key from " - + "the target storage certificate . . ." + NEWLINE, true); - - mWrapPublicKey = (PublicKey) (PK11PubKey.fromSPKI(getPublicKey() - .getEncoded())); - - if (mWrapPublicKey == null) { - log("ERROR: Failed extracting " - + "public key from target storage certificate stored in '" - + mTargetStorageCertificateFilename + "'" + NEWLINE, - true); - System.exit(0); + log( "BEGIN: Obtaining the public key from " + + "the target storage certificate . . ." + + NEWLINE, true ); + + mWrapPublicKey = ( PublicKey ) + ( PK11PubKey.fromSPKI( + getPublicKey().getEncoded() ) ); + + if( mWrapPublicKey == null ) { + log( "ERROR: Failed extracting " + + "public key from target storage certificate stored in '" + + mTargetStorageCertificateFilename + + "'" + + NEWLINE, true ); + System.exit( 0 ); } - log("FINISHED: Obtaining the public key from " - + "the target storage certificate." + NEWLINE, true); - } catch (InvalidKeyFormatException exInvalidPublicKey) { - log("ERROR: Failed extracting " - + "public key from target storage certificate stored in '" - + mTargetStorageCertificateFilename - + "' InvalidKeyFormatException '" - + exInvalidPublicKey.toString() + "'" + NEWLINE, true); - System.exit(0); + log( "FINISHED: Obtaining the public key from " + + "the target storage certificate." + + NEWLINE, true ); + } catch( InvalidKeyFormatException exInvalidPublicKey ) { + log( "ERROR: Failed extracting " + + "public key from target storage certificate stored in '" + + mTargetStorageCertificateFilename + + "' InvalidKeyFormatException '" + + exInvalidPublicKey.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } return SUCCESS; } + /** * This method basically rewraps the "wrappedKeyData" by implementiing * "mStorageUnit.decryptInternalPrivate( byte wrappedKeyData[] )" and * "mStorageUnit.encryptInternalPrivate( byte priKey[] )", where * "wrappedKeyData" uses the following structure: - * - * SEQUENCE { encryptedSession OCTET STRING, encryptedPrivate OCTET STRING } - * - * This method is based upon code from 'com.netscape.kra.EncryptionUnit'. + * + * SEQUENCE { + * encryptedSession OCTET STRING, + * encryptedPrivate OCTET STRING + * } + * + * This method is based upon code from + * 'com.netscape.kra.EncryptionUnit'. *

- * + * * @return a byte[] containing the rewrappedKeyData */ - private static byte[] rewrap_wrapped_key_data(byte[] wrappedKeyData) - throws Exception { + private static byte[] rewrap_wrapped_key_data( byte[] wrappedKeyData ) + throws Exception { DerValue val = null; DerInputStream in = null; DerValue dSession = null; @@ -1408,50 +1944,75 @@ public class DRMTool { // mStorageUnit.decryptInternalPrivate( byte wrappedKeyData[] ); // throws EBaseException try { - val = new DerValue(wrappedKeyData); + val = new DerValue( wrappedKeyData ); in = val.data; dSession = in.getDerValue(); source_session = dSession.getOctetString(); dPri = in.getDerValue(); pri = dPri.getOctetString(); - source_rsaWrap = mSourceToken.getKeyWrapper(KeyWrapAlgorithm.RSA); - source_rsaWrap.initUnwrap(mUnwrapPrivateKey, null); - sk = source_rsaWrap.unwrapSymmetric(source_session, - SymmetricKey.DES3, SymmetricKey.Usage.DECRYPT, 0); - if (mDebug) { - log("DEBUG: sk = '" - + com.netscape.osutil.OSUtil.BtoA(sk.getEncoded()) - + "' length = '" + sk.getEncoded().length + "'" - + NEWLINE, false); - log("DEBUG: pri = '" + com.netscape.osutil.OSUtil.BtoA(pri) - + "' length = '" + pri.length + "'" + NEWLINE, false); + source_rsaWrap = mSourceToken.getKeyWrapper( + KeyWrapAlgorithm.RSA ); + source_rsaWrap.initUnwrap( mUnwrapPrivateKey, null ); + sk = source_rsaWrap.unwrapSymmetric( source_session, + SymmetricKey.DES3, + SymmetricKey.Usage.DECRYPT, + 0 ); + if( mDebug ) { + log( "DEBUG: sk = '" + + com.netscape.osutil.OSUtil.BtoA( sk.getEncoded() ) + + "' length = '" + + sk.getEncoded().length + + "'" + + NEWLINE, false ); + log( "DEBUG: pri = '" + + com.netscape.osutil.OSUtil.BtoA( pri ) + + "' length = '" + + pri.length + + "'" + + NEWLINE, false ); } - } catch (IOException exUnwrapIO) { - log("ERROR: Unwrapping key data - " + "IOException: '" - + exUnwrapIO.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (NoSuchAlgorithmException exUnwrapAlgorithm) { - log("ERROR: Unwrapping key data - " - + "NoSuchAlgorithmException: '" - + exUnwrapAlgorithm.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (TokenException exUnwrapToken) { - log("ERROR: Unwrapping key data - " + "TokenException: '" - + exUnwrapToken.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (InvalidKeyException exUnwrapInvalidKey) { - log("ERROR: Unwrapping key data - " + "InvalidKeyException: '" - + exUnwrapInvalidKey.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (InvalidAlgorithmParameterException exUnwrapInvalidAlgorithm) { - log("ERROR: Unwrapping key data - " - + "InvalidAlgorithmParameterException: '" - + exUnwrapInvalidAlgorithm.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (IllegalStateException exUnwrapState) { - log("ERROR: Unwrapping key data - " + "InvalidStateException: '" - + exUnwrapState.toString() + "'" + NEWLINE, true); - System.exit(0); + } catch( IOException exUnwrapIO ) { + log( "ERROR: Unwrapping key data - " + + "IOException: '" + + exUnwrapIO.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( NoSuchAlgorithmException exUnwrapAlgorithm ) { + log( "ERROR: Unwrapping key data - " + + "NoSuchAlgorithmException: '" + + exUnwrapAlgorithm.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( TokenException exUnwrapToken ) { + log( "ERROR: Unwrapping key data - " + + "TokenException: '" + + exUnwrapToken.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( InvalidKeyException exUnwrapInvalidKey ) { + log( "ERROR: Unwrapping key data - " + + "InvalidKeyException: '" + + exUnwrapInvalidKey.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( InvalidAlgorithmParameterException exUnwrapInvalidAlgorithm ) { + log( "ERROR: Unwrapping key data - " + + "InvalidAlgorithmParameterException: '" + + exUnwrapInvalidAlgorithm.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( IllegalStateException exUnwrapState ) { + log( "ERROR: Unwrapping key data - " + + "InvalidStateException: '" + + exUnwrapState.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } // public byte[] @@ -1459,63 +2020,83 @@ public class DRMTool { // throws EBaseException try { // Use "mSourceToken" to get "KeyWrapAlgorithm.RSA" - target_rsaWrap = mSourceToken.getKeyWrapper(KeyWrapAlgorithm.RSA); - target_rsaWrap.initWrap(mWrapPublicKey, null); - target_session = target_rsaWrap.wrap(sk); + target_rsaWrap = mSourceToken.getKeyWrapper( + KeyWrapAlgorithm.RSA ); + target_rsaWrap.initWrap( mWrapPublicKey, null ); + target_session = target_rsaWrap.wrap( sk ); tmp = new DerOutputStream(); out = new DerOutputStream(); - tmp.putOctetString(target_session); - tmp.putOctetString(pri); - out.write(DerValue.tag_Sequence, tmp); + tmp.putOctetString( target_session ); + tmp.putOctetString( pri ); + out.write( DerValue.tag_Sequence, tmp ); rewrappedKeyData = out.toByteArray(); - } catch (NoSuchAlgorithmException exWrapAlgorithm) { - log("ERROR: Wrapping key data - " + "NoSuchAlgorithmException: '" - + exWrapAlgorithm.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (TokenException exWrapToken) { - log("ERROR: Wrapping key data - " + "TokenException: '" - + exWrapToken.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (InvalidKeyException exWrapInvalidKey) { - log("ERROR: Wrapping key data - " + "InvalidKeyException: '" - + exWrapInvalidKey.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (InvalidAlgorithmParameterException exWrapInvalidAlgorithm) { - log("ERROR: Wrapping key data - " - + "InvalidAlgorithmParameterException: '" - + exWrapInvalidAlgorithm.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (IllegalStateException exWrapState) { - log("ERROR: Wrapping key data - " + "InvalidStateException: '" - + exWrapState.toString() + "'" + NEWLINE, true); - System.exit(0); - } catch (IOException exWrapIO) { - log("ERROR: Wrapping key data - " + "IOException: '" - + exWrapIO.toString() + "'" + NEWLINE, true); - System.exit(0); + } catch( NoSuchAlgorithmException exWrapAlgorithm ) { + log( "ERROR: Wrapping key data - " + + "NoSuchAlgorithmException: '" + + exWrapAlgorithm.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( TokenException exWrapToken ) { + log( "ERROR: Wrapping key data - " + + "TokenException: '" + + exWrapToken.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( InvalidKeyException exWrapInvalidKey ) { + log( "ERROR: Wrapping key data - " + + "InvalidKeyException: '" + + exWrapInvalidKey.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( InvalidAlgorithmParameterException exWrapInvalidAlgorithm ) { + log( "ERROR: Wrapping key data - " + + "InvalidAlgorithmParameterException: '" + + exWrapInvalidAlgorithm.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( IllegalStateException exWrapState ) { + log( "ERROR: Wrapping key data - " + + "InvalidStateException: '" + + exWrapState.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( IOException exWrapIO ) { + log( "ERROR: Wrapping key data - " + + "IOException: '" + + exWrapIO.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } return rewrappedKeyData; } + /** - * Helper method used to remove all EOLs ('\n' and '\r') from the passed in - * string. + * Helper method used to remove all EOLs ('\n' and '\r') + * from the passed in string. *

- * + * * @param data consisting of a string containing EOLs * @return a string consisting of a string with no EOLs */ - private static String stripEOL(String data) { + private static String stripEOL( String data ) { StringBuffer buffer = new StringBuffer(); String revised_data = null; - for (int i = 0; i < data.length(); i++) { - if ((data.charAt(i) != '\n') && (data.charAt(i) != '\r')) { - buffer.append(data.charAt(i)); + for( int i = 0; i < data.length(); i++ ) { + if( ( data.charAt(i) != '\n' ) && + ( data.charAt(i) != '\r' ) ) { + buffer.append( data.charAt( i ) ); } } @@ -1524,23 +2105,25 @@ public class DRMTool { return revised_data; } + /** - * Helper method used to format a string containing unformatted data into a - * string containing formatted data suitable as an entry for an LDIF file. + * Helper method used to format a string containing unformatted data + * into a string containing formatted data suitable as an entry for + * an LDIF file. *

- * + * * @param length the length of the first line of data * @param data a string containing unformatted data * @return formatted data consisting of data formatted for an LDIF record - * suitable for an LDIF file + * suitable for an LDIF file */ - private static String format_ldif_data(int length, String data) { + private static String format_ldif_data( int length, String data ) { String revised_data = ""; - if (data.length() > length) { + if( data.length() > length ) { // process first line - for (int i = 0; i < length; i++) { - revised_data += data.charAt(i); + for( int i = 0; i < length; i++ ) { + revised_data += data.charAt( i ); } // terminate first line @@ -1548,101 +2131,104 @@ public class DRMTool { // process remaining lines int j = 0; - for (int i = length; i < data.length(); i++) { - if (j == 0) { + for( int i = length; i < data.length(); i++ ) { + if( j == 0 ) { revised_data += ' '; } - revised_data += data.charAt(i); + revised_data += data.charAt( i ); j++; - if (j == 76) { + if( j == 76 ) { revised_data += '\n'; j = 0; } } } - return revised_data.replaceAll("\\s+$", ""); + return revised_data.replaceAll( "\\s+$", "" ); } + /*********************/ /* ID Offset Methods */ /*********************/ /** - * Helper method which converts an "indexed" BigInteger into its String - * representation. - * + * Helper method which converts an "indexed" BigInteger into + * its String representation. + * *

-     * 
+     *
      *     NOTE:  Indexed data means that the numeric data
      *            is stored with a prepended length
      *            (e. g. - record '73' is stored as '0273').
-     * 
+     *
      *            Indexed data is currently limited to '99' digits
      *            (an index of '00' is invalid).  See
      *            'com.netscape.cmscore.dbs.BigIntegerMapper.java'
      *            for details.
-     * 
+     *
      * 
- * + * * This method is based upon code from * 'com.netscape.cmscore.dbs.BigIntegerMapper'. *

- * + * * @param i an "indexed " BigInteger * @return the string representation of the "indexed" BigInteger */ - private static String BigIntegerToDB(BigInteger i) { + private static String BigIntegerToDB( BigInteger i ) { int len = i.toString().length(); String ret = null; - if (len < 10) { - ret = "0" + Integer.toString(len) + i.toString(); + if( len < 10 ) { + ret = "0" + Integer.toString( len ) + i.toString(); } else { - ret = Integer.toString(len) + i.toString(); + ret = Integer.toString( len ) + i.toString(); } return ret; } + /** - * Helper method which converts the string representation of an "indexed" - * integer into a BigInteger. - * + * Helper method which converts the string representation of an + * "indexed" integer into a BigInteger. + * *

      *     NOTE:  Indexed data means that the numeric data
      *            is stored with a prepended length
      *            (e. g. - record '73' is stored as '0273').
-     * 
+     *
      *            Indexed data is currently limited to '99' digits
      *            (an index of '00' is invalid).  See
      *            'com.netscape.cmscore.dbs.BigIntegerMapper.java'
      *            for details.
      * 
- * + * * This method is based upon code from * 'com.netscape.cmscore.dbs.BigIntegerMapper'. *

- * + * * @param i the string representation of the "indexed" integer * @return an "indexed " BigInteger */ - private static BigInteger BigIntegerFromDB(String i) { - String s = i.substring(2); + private static BigInteger BigIntegerFromDB( String i ) { + String s = i.substring( 2 ); // possibly check length - return new BigInteger(s); + return new BigInteger( s ); } + /** * This method accepts an "attribute", its "delimiter", a string - * representation of numeric data, and a flag indicating whether or not the - * string representation is "indexed". - * + * representation of numeric data, and a flag indicating whether + * or not the string representation is "indexed". + * * An "attribute" consists of one of the following values: - * + * *

      *     DRM_LDIF_CN = "cn:";
      *     DRM_LDIF_DN_EMBEDDED_CN_DATA = "dn: cn";
@@ -1651,29 +2237,31 @@ public class DRMTool {
      *     DRM_LDIF_EXTDATA_SERIAL_NUMBER = "extdata-serialnumber:";
      *     DRM_LDIF_REQUEST_ID = "requestId:";
      *     DRM_LDIF_SERIAL_NO = "serialno:";
-     * 
-     * 
+     *
+     *
      *     NOTE:  Indexed data means that the numeric data
      *            is stored with a prepended length
      *            (e. g. - record '73' is stored as '0273').
-     * 
+     *
      *            Indexed data is currently limited to '99' digits
      *            (an index of '00' is invalid).  See
      *            'com.netscape.cmscore.dbs.BigIntegerMapper.java'
      *            for details.
      * 
- * + * *

- * + * * @param attribute the string representation of the "name" * @param delimiter the separator between the attribute and its contents * @param source_line the string containing the "name" and "value" * @param indexed boolean flag indicating if the "value" is "indexed" * @return a revised line containing the "name" and "value" with the - * specified ID offset applied as a "mask" to the "value" + * specified ID offset applied as a "mask" to the "value" */ - private static String compose_numeric_line(String attribute, - String delimiter, String source_line, boolean indexed) { + private static String compose_numeric_line( String attribute, + String delimiter, + String source_line, + boolean indexed ) { String target_line = null; String data = null; String revised_data = null; @@ -1681,75 +2269,84 @@ public class DRMTool { // Since both "-append_id_offset" and "-remove_id_offset" are OPTIONAL // parameters, first check to see if either has been selected - if (!mAppendIdOffsetFlag && !mRemoveIdOffsetFlag) { + if( !mAppendIdOffsetFlag && + !mRemoveIdOffsetFlag ) { return source_line; } try { // extract the data - data = source_line.substring(attribute.length() + 1).trim(); + data = source_line.substring( attribute.length() + 1 ).trim(); // skip values which are non-numeric - if (!data.matches("[0-9]++")) { + if( !data.matches( "[0-9]++" ) ) { // set the target_line to the unchanged source_line target_line = source_line; // log this information - log("Skipped changing non-numeric line '" + source_line + "'." - + NEWLINE, false); + log( "Skipped changing non-numeric line '" + + source_line + + "'." + + NEWLINE, false ); } else { // if indexed, first strip the index from the data - if (indexed) { - // NOTE: Indexed data means that the numeric data - // is stored with a prepended length - // (e. g. - record '73' is stored as '0273'). + if( indexed ) { + // NOTE: Indexed data means that the numeric data + // is stored with a prepended length + // (e. g. - record '73' is stored as '0273'). // - // Indexed data is currently limited to '99' digits - // (an index of '00' is invalid). See - // 'com.netscape.cmscore.dbs.BigIntegerMapper.java' - // for details. - value = BigIntegerFromDB(data); + // Indexed data is currently limited to '99' digits + // (an index of '00' is invalid). See + // 'com.netscape.cmscore.dbs.BigIntegerMapper.java' + // for details. + value = BigIntegerFromDB( data ); } else { - value = new BigInteger(data); + value = new BigInteger( data ); } // compare the specified target ID offset // with the actual value of the attribute - if (mAppendIdOffsetFlag) { - if (mAppendIdOffset.compareTo(value) == 1) { + if( mAppendIdOffsetFlag ) { + if( mAppendIdOffset.compareTo( value ) == 1 ) { // add the target ID offset to this value - if (indexed) { + if( indexed ) { revised_data = BigIntegerToDB( - value.add(mAppendIdOffset)).toString(); + value.add( mAppendIdOffset ) + ).toString(); } else { - revised_data = value.add(mAppendIdOffset) - .toString(); + revised_data = value.add( + mAppendIdOffset ).toString(); } } else { - log("ERROR: attribute='" + attribute - + "' is greater than the specified " - + "append_id_offset='" - + mAppendIdOffset.toString() + "'!" + NEWLINE, - true); - System.exit(0); + log( "ERROR: attribute='" + + attribute + + "' is greater than the specified " + + "append_id_offset='" + + mAppendIdOffset.toString() + + "'!" + + NEWLINE, true ); + System.exit( 0 ); } - } else if (mRemoveIdOffsetFlag) { - if (mRemoveIdOffset.compareTo(value) <= 0) { + } else if( mRemoveIdOffsetFlag ) { + if( mRemoveIdOffset.compareTo( value ) <= 0 ) { // subtract the target ID offset to this value - if (indexed) { + if( indexed ) { revised_data = BigIntegerToDB( - value.subtract(mRemoveIdOffset)).toString(); + value.subtract( mRemoveIdOffset ) + ).toString(); } else { - revised_data = value.subtract(mRemoveIdOffset) - .toString(); + revised_data = value.subtract( mRemoveIdOffset + ).toString(); } } else { - log("ERROR: attribute='" + attribute - + "' is less than the specified " - + "remove_id_offset='" - + mRemoveIdOffset.toString() + "'!" + NEWLINE, - true); - System.exit(0); + log( "ERROR: attribute='" + + attribute + + "' is less than the specified " + + "remove_id_offset='" + + mRemoveIdOffset.toString() + + "'!" + + NEWLINE, true ); + System.exit( 0 ); } } @@ -1757,23 +2354,35 @@ public class DRMTool { target_line = attribute + delimiter + revised_data; // log this information - log("Changed numeric data '" + data + "' to '" + revised_data - + "'." + NEWLINE, false); + log( "Changed numeric data '" + + data + + "' to '" + + revised_data + + "'." + + NEWLINE, false ); } - } catch (IndexOutOfBoundsException exBounds) { - log("ERROR: source_line='" + source_line - + "' IndexOutOfBoundsException: '" + exBounds.toString() - + "'" + NEWLINE, true); - System.exit(0); - } catch (PatternSyntaxException exPattern) { - log("ERROR: data='" + data + "' PatternSyntaxException: '" - + exPattern.toString() + "'" + NEWLINE, true); - System.exit(0); + } catch( IndexOutOfBoundsException exBounds ) { + log( "ERROR: source_line='" + + source_line + + "' IndexOutOfBoundsException: '" + + exBounds.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); + } catch( PatternSyntaxException exPattern ) { + log( "ERROR: data='" + + data + + "' PatternSyntaxException: '" + + exPattern.toString() + + "'" + + NEWLINE, true ); + System.exit( 0 ); } return target_line; } + /***********************/ /* LDIF Parser Methods */ /***********************/ @@ -1781,133 +2390,189 @@ public class DRMTool { /** * Helper method which composes the output line for DRM_LDIF_CN. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_cn(String record_type, String line) { + private static String output_cn( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { - if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_CN)) { - output = compose_numeric_line(DRM_LDIF_CN, SPACE, line, false); + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_CN ) ) { + output = compose_numeric_line( DRM_LDIF_CN, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_CN)) { - output = compose_numeric_line(DRM_LDIF_CN, SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_CN ) ) { + output = compose_numeric_line( DRM_LDIF_CN, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_CN)) { - output = compose_numeric_line(DRM_LDIF_CN, SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_CN ) ) { + output = compose_numeric_line( DRM_LDIF_CN, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_CN)) { - output = compose_numeric_line(DRM_LDIF_CN, SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_CN ) ) { + output = compose_numeric_line( DRM_LDIF_CN, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_CN)) { - output = compose_numeric_line(DRM_LDIF_CN, SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_CN ) ) { + output = compose_numeric_line( DRM_LDIF_CN, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECORD)) { + } else if( record_type.equals( DRM_LDIF_RECORD ) ) { // Non-Request / Non-Key Record: - // Pass through the original - // 'cn' line UNCHANGED - // so that it is ALWAYS written + // Pass through the original + // 'cn' line UNCHANGED + // so that it is ALWAYS written output = line; } else { - log("ERROR: Mismatched record field='" + DRM_LDIF_CN - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_CN + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for DRM_LDIF_DATE_OF_MODIFY. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_date_of_modify(String record_type, String line) { + private static String output_date_of_modify( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { - if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY)) { - output = DRM_LDIF_DATE_OF_MODIFY + SPACE + mDateOfModify; - - log("Changed '" + line + "' to '" + output + "'." + NEWLINE, - false); + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY ) ) { + output = DRM_LDIF_DATE_OF_MODIFY + + SPACE + + mDateOfModify; + + log( "Changed '" + + line + + "' to '" + + output + + "'." + + NEWLINE, false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY)) { - output = DRM_LDIF_DATE_OF_MODIFY + SPACE + mDateOfModify; - - log("Changed '" + line + "' to '" + output + "'." + NEWLINE, - false); + } else if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY ) ) { + output = DRM_LDIF_DATE_OF_MODIFY + + SPACE + + mDateOfModify; + + log( "Changed '" + + line + + "' to '" + + output + + "'." + + NEWLINE, false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY)) { - output = DRM_LDIF_DATE_OF_MODIFY + SPACE + mDateOfModify; - - log("Changed '" + line + "' to '" + output + "'." + NEWLINE, - false); + } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY ) ) { + output = DRM_LDIF_DATE_OF_MODIFY + + SPACE + + mDateOfModify; + + log( "Changed '" + + line + + "' to '" + + output + + "'." + + NEWLINE, false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY)) { - output = DRM_LDIF_DATE_OF_MODIFY + SPACE + mDateOfModify; - - log("Changed '" + line + "' to '" + output + "'." + NEWLINE, - false); + } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY ) ) { + output = DRM_LDIF_DATE_OF_MODIFY + + SPACE + + mDateOfModify; + + log( "Changed '" + + line + + "' to '" + + output + + "'." + + NEWLINE, false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY)) { - output = DRM_LDIF_DATE_OF_MODIFY + SPACE + mDateOfModify; - - log("Changed '" + line + "' to '" + output + "'." + NEWLINE, - false); + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY ) ) { + output = DRM_LDIF_DATE_OF_MODIFY + + SPACE + + mDateOfModify; + + log( "Changed '" + + line + + "' to '" + + output + + "'." + + NEWLINE, false ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" + DRM_LDIF_DATE_OF_MODIFY - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_DATE_OF_MODIFY + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for DRM_LDIF_DN. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_dn(String record_type, String line) { + private static String output_dn( String record_type, + String line ) { String data = null; String embedded_cn_data[] = null; String embedded_cn_output = null; @@ -1915,24 +2580,27 @@ public class DRMTool { String output = null; try { - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { - if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_DN)) { + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_DN ) ) { // First check for an embedded "cn=" // name-value pair - if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) { + if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) { // At this point, always extract // the embedded "cn=" name-value pair // which will ALWAYS be the first // portion of the "dn: " attribute - embedded_cn_data = line.split(COMMA, 2); + embedded_cn_data = line.split( COMMA, 2 ); embedded_cn_output = compose_numeric_line( - DRM_LDIF_DN_EMBEDDED_CN_DATA, EQUAL_SIGN, - embedded_cn_data[0], false); - - input = embedded_cn_output + COMMA - + embedded_cn_data[1]; + DRM_LDIF_DN_EMBEDDED_CN_DATA, + EQUAL_SIGN, + embedded_cn_data[0], + false ); + + input = embedded_cn_output + + COMMA + + embedded_cn_data[1]; } else { input = line; } @@ -1941,33 +2609,36 @@ public class DRMTool { // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this portion of the field // if both of these options have been selected - if (mDrmNamingContextsFlag) { - output = input.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = input.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = input; } } else { output = line; } - } else if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_DN)) { + } else if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_DN ) ) { // First check for an embedded "cn=" // name-value pair - if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) { + if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) { // At this point, always extract // the embedded "cn=" name-value pair // which will ALWAYS be the first // portion of the "dn: " attribute - embedded_cn_data = line.split(COMMA, 2); + embedded_cn_data = line.split( COMMA, 2 ); embedded_cn_output = compose_numeric_line( - DRM_LDIF_DN_EMBEDDED_CN_DATA, EQUAL_SIGN, - embedded_cn_data[0], false); - - input = embedded_cn_output + COMMA - + embedded_cn_data[1]; + DRM_LDIF_DN_EMBEDDED_CN_DATA, + EQUAL_SIGN, + embedded_cn_data[0], + false ); + + input = embedded_cn_output + + COMMA + + embedded_cn_data[1]; } else { input = line; } @@ -1976,33 +2647,36 @@ public class DRMTool { // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this portion of the field // if both of these options have been selected - if (mDrmNamingContextsFlag) { - output = input.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = input.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = input; } } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_DN)) { + } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_DN ) ) { // First check for an embedded "cn=" // name-value pair - if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) { + if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) { // At this point, always extract // the embedded "cn=" name-value pair // which will ALWAYS be the first // portion of the "dn: " attribute - embedded_cn_data = line.split(COMMA, 2); + embedded_cn_data = line.split( COMMA, 2 ); embedded_cn_output = compose_numeric_line( - DRM_LDIF_DN_EMBEDDED_CN_DATA, EQUAL_SIGN, - embedded_cn_data[0], false); - - input = embedded_cn_output + COMMA - + embedded_cn_data[1]; + DRM_LDIF_DN_EMBEDDED_CN_DATA, + EQUAL_SIGN, + embedded_cn_data[0], + false ); + + input = embedded_cn_output + + COMMA + + embedded_cn_data[1]; } else { input = line; } @@ -2011,33 +2685,36 @@ public class DRMTool { // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this portion of the field // if both of these options have been selected - if (mDrmNamingContextsFlag) { - output = input.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = input.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = input; } } else { output = line; } - } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_DN)) { + } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_DN ) ) { // First check for an embedded "cn=" // name-value pair - if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) { + if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) { // At this point, always extract // the embedded "cn=" name-value pair // which will ALWAYS be the first // portion of the "dn: " attribute - embedded_cn_data = line.split(COMMA, 2); + embedded_cn_data = line.split( COMMA, 2 ); embedded_cn_output = compose_numeric_line( - DRM_LDIF_DN_EMBEDDED_CN_DATA, EQUAL_SIGN, - embedded_cn_data[0], false); - - input = embedded_cn_output + COMMA - + embedded_cn_data[1]; + DRM_LDIF_DN_EMBEDDED_CN_DATA, + EQUAL_SIGN, + embedded_cn_data[0], + false ); + + input = embedded_cn_output + + COMMA + + embedded_cn_data[1]; } else { input = line; } @@ -2046,33 +2723,36 @@ public class DRMTool { // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this portion of the field // if both of these options have been selected - if (mDrmNamingContextsFlag) { - output = input.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = input.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = input; } } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_DN)) { + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_DN ) ) { // First check for an embedded "cn=" // name-value pair - if (line.startsWith(DRM_LDIF_DN_EMBEDDED_CN_DATA)) { + if( line.startsWith( DRM_LDIF_DN_EMBEDDED_CN_DATA ) ) { // At this point, always extract // the embedded "cn=" name-value pair // which will ALWAYS be the first // portion of the "dn: " attribute - embedded_cn_data = line.split(COMMA, 2); + embedded_cn_data = line.split( COMMA, 2 ); embedded_cn_output = compose_numeric_line( - DRM_LDIF_DN_EMBEDDED_CN_DATA, EQUAL_SIGN, - embedded_cn_data[0], false); - - input = embedded_cn_output + COMMA - + embedded_cn_data[1]; + DRM_LDIF_DN_EMBEDDED_CN_DATA, + EQUAL_SIGN, + embedded_cn_data[0], + false ); + + input = embedded_cn_output + + COMMA + + embedded_cn_data[1]; } else { input = line; } @@ -2081,129 +2761,155 @@ public class DRMTool { // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this portion of the field // if both of these options have been selected - if (mDrmNamingContextsFlag) { - output = input.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = input.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = input; } } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECORD)) { + } else if( record_type.equals( DRM_LDIF_RECORD ) ) { // Non-Request / Non-Key Record: - // Pass through the original - // 'dn' line UNCHANGED - // so that it is ALWAYS written + // Pass through the original + // 'dn' line UNCHANGED + // so that it is ALWAYS written output = line; } else { - log("ERROR: Mismatched record field='" + DRM_LDIF_DN - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_DN + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } - } catch (PatternSyntaxException exDnEmbeddedCnNameValuePattern) { - log("ERROR: line='" + line + "' PatternSyntaxException: '" - + exDnEmbeddedCnNameValuePattern.toString() + "'" + NEWLINE, - true); - } catch (NullPointerException exNullPointerException) { - log("ERROR: Unable to replace source DRM naming context '" - + mSourceDrmNamingContext - + "' with target DRM naming context '" - + mTargetDrmNamingContext + "' NullPointerException: '" - + exNullPointerException.toString() + "'" + NEWLINE, true); + } catch( PatternSyntaxException exDnEmbeddedCnNameValuePattern ) { + log( "ERROR: line='" + + line + + "' PatternSyntaxException: '" + + exDnEmbeddedCnNameValuePattern.toString() + + "'" + + NEWLINE, true ); + } catch( NullPointerException exNullPointerException ) { + log( "ERROR: Unable to replace source DRM naming context '" + + mSourceDrmNamingContext + + "' with target DRM naming context '" + + mTargetDrmNamingContext + + "' NullPointerException: '" + + exNullPointerException.toString() + + "'" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_KEY_RECORD. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_extdata_key_record(String record_type, - String line) { + private static String output_extdata_key_record( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { - if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD)) { - output = compose_numeric_line(DRM_LDIF_EXTDATA_KEY_RECORD, - SPACE, line, false); + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD ) ) { + output = compose_numeric_line( DRM_LDIF_EXTDATA_KEY_RECORD, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD)) { - output = compose_numeric_line(DRM_LDIF_EXTDATA_KEY_RECORD, - SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD ) ) { + output = compose_numeric_line( DRM_LDIF_EXTDATA_KEY_RECORD, + SPACE, + line, + false ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_EXTDATA_KEY_RECORD + "' for record type='" - + record_type + "'!" + NEWLINE, true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_EXTDATA_KEY_RECORD + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_REQUEST_ID. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_extdata_request_id(String record_type, - String line) { + private static String output_extdata_request_id( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { // ALWAYS pass-through "extdata-requestId" for // DRM_LDIF_ENROLLMENT records UNCHANGED because the // value in this field is associated with the issuing CA! output = line; - } else if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID)) { - output = compose_numeric_line(DRM_LDIF_EXTDATA_REQUEST_ID, - SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID ) ) { + output = compose_numeric_line( DRM_LDIF_EXTDATA_REQUEST_ID, + SPACE, + line, + false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID)) { - output = compose_numeric_line(DRM_LDIF_EXTDATA_REQUEST_ID, - SPACE, line, false); + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID ) ) { + output = compose_numeric_line( DRM_LDIF_EXTDATA_REQUEST_ID, + SPACE, + line, + false ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_EXTDATA_REQUEST_ID + "' for record type='" - + record_type + "'!" + NEWLINE, true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_EXTDATA_REQUEST_ID + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_REQUEST_NOTES. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_extdata_request_notes(String record_type, - String line) { + private static String output_extdata_request_notes( String record_type, + String line ) { String input = null; String data = null; String unformatted_data = null; @@ -2211,669 +2917,889 @@ public class DRMTool { String next_line = null; // extract the data - if (line.length() > DRM_LDIF_EXTDATA_REQUEST_NOTES.length()) { - input = line.substring(DRM_LDIF_EXTDATA_REQUEST_NOTES.length() + 1) - .trim(); + if( line.length() > DRM_LDIF_EXTDATA_REQUEST_NOTES.length() ) { + input = line.substring( + DRM_LDIF_EXTDATA_REQUEST_NOTES.length() + 1 + ).trim(); } else { - input = line.substring(DRM_LDIF_EXTDATA_REQUEST_NOTES.length()) - .trim(); + input = line.substring( + DRM_LDIF_EXTDATA_REQUEST_NOTES.length() + ).trim(); } - while ((line = ldif_record.next()) != null) { - if (line.startsWith(SPACE)) { + while( ( line = ldif_record.next() ) != null ) { + if( line.startsWith( SPACE ) ) { // Do NOT use "trim()"; // remove single leading space and // trailing carriage returns and newlines ONLY! - input += line.replaceFirst(" ", "").replace('\r', '\0') - .replace('\n', '\0'); + input += line.replaceFirst(" ","").replace('\r','\0').replace('\n','\0'); } else { next_line = line; break; } } - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { - if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES)) { + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { + if(drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES )) { // write out a revised 'extdata-requestnotes' line - if (mRewrapFlag && mAppendIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage + SPACE - + PLUS + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE + TIC - + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + if( mRewrapFlag && mAppendIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage + SPACE - + PLUS + SPACE + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE - + SPACE + TIC + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mAppendIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE + TIC - + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mAppendIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRemoveIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + SPACE + TIC - + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRemoveIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); } // log this information - log("Changed:" - + NEWLINE - + TIC - + DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - input) + TIC + NEWLINE + "--->" + NEWLINE + TIC - + output + TIC + NEWLINE, false); + log( "Changed:" + + NEWLINE + + TIC + + DRM_LDIF_EXTDATA_REQUEST_NOTES + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + input ) + + TIC + + NEWLINE + + "--->" + + NEWLINE + + TIC + + output + + TIC + + NEWLINE, false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES)) { + } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES ) ) { // write out a revised 'extdata-requestnotes' line - if (mRewrapFlag && mAppendIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage + SPACE - + PLUS + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE + TIC - + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + if( mRewrapFlag && mAppendIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage + SPACE - + PLUS + SPACE + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE - + SPACE + TIC + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mAppendIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE + TIC - + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mAppendIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRemoveIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + SPACE + TIC - + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRemoveIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); } // log this information - log("Changed:" - + NEWLINE - + TIC - + DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - input) + TIC + NEWLINE + "--->" + NEWLINE + TIC - + output + TIC + NEWLINE, false); + log( "Changed:" + + NEWLINE + + TIC + + DRM_LDIF_EXTDATA_REQUEST_NOTES + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + input ) + + TIC + + NEWLINE + + "--->" + + NEWLINE + + TIC + + output + + TIC + + NEWLINE, false ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES)) { + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES ) ) { // write out a revised 'extdata-requestnotes' line - if (mRewrapFlag && mAppendIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage + SPACE - + PLUS + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE + TIC - + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + if( mRewrapFlag && mAppendIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage + SPACE - + PLUS + SPACE + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE - + SPACE + TIC + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REWRAP_MESSAGE + mPublicKeySize - + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mAppendIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE + TIC - + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mAppendIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRemoveIdOffsetFlag) { - data = input + SPACE + LEFT_BRACE + mDateOfModify - + RIGHT_BRACE + COLON + SPACE - + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + SPACE + TIC - + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRemoveIdOffsetFlag ) { + data = input + + SPACE + + LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); } // log this information - log("Changed:" - + NEWLINE - + TIC - + DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - input) + TIC + NEWLINE + "--->" + NEWLINE + TIC - + output + TIC + NEWLINE, false); + log( "Changed:" + + NEWLINE + + TIC + + DRM_LDIF_EXTDATA_REQUEST_NOTES + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + input ) + + TIC + + NEWLINE + + "--->" + + NEWLINE + + TIC + + output + + TIC + + NEWLINE, false ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_EXTDATA_REQUEST_NOTES + "' for record type='" - + record_type + "'!" + NEWLINE, true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_EXTDATA_REQUEST_NOTES + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } - if (output != null) { + if( output != null ) { output += NEWLINE + next_line; } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_REQUEST_NOTES. *

- * + * * @param record_type the string representation of the input record type * @param previous_line the string representation of the previous input line * @param writer the PrintWriter used to output this new LDIF line * @return the composed output line */ - private static void create_extdata_request_notes(String record_type, - String previous_line, PrintWriter writer) { + private static void create_extdata_request_notes( String record_type, + String previous_line, + PrintWriter writer ) { String data = null; String unformatted_data = null; String output = null; - if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES)) { - if (!previous_line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) { + if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES ) ) { + if(!previous_line.startsWith( DRM_LDIF_EXTDATA_REQUEST_NOTES)) { // write out the missing 'extdata-requestnotes' line - if (mRewrapFlag && mAppendIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REWRAP_MESSAGE - + mPublicKeySize + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + SPACE + PLUS + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE - + TIC + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + if( mRewrapFlag && mAppendIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REWRAP_MESSAGE - + mPublicKeySize + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + SPACE + PLUS + SPACE - + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + SPACE - + TIC + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REWRAP_MESSAGE - + mPublicKeySize + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mAppendIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE - + SPACE + TIC + mAppendIdOffset.toString() - + TIC + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mAppendIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRemoveIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE - + SPACE + TIC + mRemoveIdOffset.toString() - + TIC + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRemoveIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); } // log this information - log("Created:" + NEWLINE + TIC + output + TIC + NEWLINE, - false); + log( "Created:" + + NEWLINE + + TIC + + output + + TIC + + NEWLINE, false ); // Write out this revised line // and flush the buffer - writer.write(output + NEWLINE); + writer.write( output + NEWLINE ); writer.flush(); - System.out.print("."); + System.out.print( "." ); } } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES)) { - if (!previous_line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) { + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES ) ) { + if(!previous_line.startsWith( DRM_LDIF_EXTDATA_REQUEST_NOTES)) { // write out the missing 'extdata-requestnotes' line - if (mRewrapFlag && mAppendIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REWRAP_MESSAGE - + mPublicKeySize + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + SPACE + PLUS + SPACE - + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + SPACE - + TIC + mAppendIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + if( mRewrapFlag && mAppendIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REWRAP_MESSAGE - + mPublicKeySize + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + SPACE + PLUS + SPACE - + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + SPACE - + TIC + mRemoveIdOffset.toString() + TIC - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + SPACE + + PLUS + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRewrapFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REWRAP_MESSAGE - + mPublicKeySize + DRM_LDIF_RSA_MESSAGE - + mSourcePKISecurityDatabasePwdfileMessage - + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRewrapFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REWRAP_MESSAGE + + mPublicKeySize + + DRM_LDIF_RSA_MESSAGE + + mSourcePKISecurityDatabasePwdfileMessage + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mAppendIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE - + SPACE + TIC + mAppendIdOffset.toString() - + TIC + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mAppendIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_APPENDED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mAppendIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); - } else if (mRemoveIdOffsetFlag) { - data = LEFT_BRACE + mDateOfModify + RIGHT_BRACE + COLON - + SPACE + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE - + SPACE + TIC + mRemoveIdOffset.toString() - + TIC + mDrmNamingContextMessage - + mProcessRequestsAndKeyRecordsOnlyMessage; + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); + } else if( mRemoveIdOffsetFlag ) { + data = LEFT_BRACE + + mDateOfModify + + RIGHT_BRACE + + COLON + SPACE + + DRM_LDIF_REMOVED_ID_OFFSET_MESSAGE + + SPACE + + TIC + + mRemoveIdOffset.toString() + + TIC + + mDrmNamingContextMessage + + mProcessRequestsAndKeyRecordsOnlyMessage; // Unformat the data - unformatted_data = stripEOL(data); + unformatted_data = stripEOL( data ); // Format the unformatted_data // to match the desired LDIF format output = DRM_LDIF_EXTDATA_REQUEST_NOTES - + SPACE - + format_ldif_data( - EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, - unformatted_data); + + SPACE + + format_ldif_data( + EXTDATA_REQUEST_NOTES_FIRST_LINE_DATA_LENGTH, + unformatted_data ); } // log this information - log("Created:" + NEWLINE + TIC + output + TIC + NEWLINE, - false); + log( "Created:" + + NEWLINE + + TIC + + output + + TIC + + NEWLINE, false ); // Write out this revised line // and flush the buffer - writer.write(output + NEWLINE); + writer.write( output + NEWLINE ); writer.flush(); - System.out.print("."); + System.out.print( "." ); } } } } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_SERIAL_NUMBER. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_extdata_serial_number(String record_type, - String line) { + private static String output_extdata_serial_number( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER)) { - output = compose_numeric_line(DRM_LDIF_EXTDATA_SERIAL_NUMBER, - SPACE, line, false); + if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER ) ) { + output = compose_numeric_line( DRM_LDIF_EXTDATA_SERIAL_NUMBER, + SPACE, + line, + false ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_EXTDATA_SERIAL_NUMBER + "' for record type='" - + record_type + "'!" + NEWLINE, true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_EXTDATA_SERIAL_NUMBER + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_PRIVATE_KEY_DATA. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_private_key_data(String record_type, - String line) { + private static String output_private_key_data( String record_type, + String line ) { byte source_wrappedKeyData[] = null; byte target_wrappedKeyData[] = null; String data = null; @@ -2883,21 +3809,22 @@ public class DRMTool { String output = null; try { - if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA)) { + if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) { + if(drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA)) { // Since "-source_pki_security_database_path", // "-source_storage_token_name", // "-source_storage_certificate_nickname", and // "-target_storage_certificate_file" are OPTIONAL // parameters, ONLY process this field if all of // these options have been selected - if (mRewrapFlag) { + if( mRewrapFlag ) { // extract the data data = line.substring( - DRM_LDIF_PRIVATE_KEY_DATA.length() + 1).trim(); + DRM_LDIF_PRIVATE_KEY_DATA.length() + 1 + ).trim(); - while ((line = ldif_record.next()) != null) { - if (line.startsWith(SPACE)) { + while( ( line = ldif_record.next() ) != null ) { + if( line.startsWith( SPACE ) ) { data += line.trim(); } else { break; @@ -2907,57 +3834,71 @@ public class DRMTool { // Decode the ASCII BASE 64 certificate // enclosed in the String() object // into a BINARY BASE 64 byte[] object - source_wrappedKeyData = com.netscape.osutil.OSUtil - .AtoB(data); + source_wrappedKeyData = + com.netscape.osutil.OSUtil.AtoB( data ); // rewrap the source wrapped private key data - target_wrappedKeyData = rewrap_wrapped_key_data(source_wrappedKeyData); + target_wrappedKeyData = rewrap_wrapped_key_data( + source_wrappedKeyData ); // Encode the BINARY BASE 64 byte[] object // into an ASCII BASE 64 certificate // enclosed in a String() object - revised_data = com.netscape.osutil.OSUtil - .BtoA(target_wrappedKeyData); + revised_data = com.netscape.osutil.OSUtil.BtoA( + target_wrappedKeyData ); // Unformat the ASCII BASE 64 certificate // for the log file - unformatted_data = stripEOL(revised_data); + unformatted_data = stripEOL( revised_data ); // Format the ASCII BASE 64 certificate // to match the desired LDIF format formatted_data = format_ldif_data( - PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH, - unformatted_data); + PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH, + unformatted_data ); // construct a revised 'privateKeyData' line - output = DRM_LDIF_PRIVATE_KEY_DATA + SPACE - + formatted_data + NEWLINE + line; + output = DRM_LDIF_PRIVATE_KEY_DATA + + SPACE + + formatted_data + + NEWLINE + + line; // log this information - log("Changed 'privateKeyData' from:" + NEWLINE + TIC - + data + TIC + NEWLINE + " to:" + NEWLINE + TIC - + unformatted_data + TIC + NEWLINE, false); + log( "Changed 'privateKeyData' from:" + + NEWLINE + + TIC + + data + + TIC + + NEWLINE + + " to:" + + NEWLINE + + TIC + + unformatted_data + + TIC + + NEWLINE, false ); } else { output = line; } } else { output = line; } - } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA)) { + } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) { + if(drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA)){ // Since "-source_pki_security_database_path", // "-source_storage_token_name", // "-source_storage_certificate_nickname", and // "-target_storage_certificate_file" are OPTIONAL // parameters, ONLY process this field if all of // these options have been selected - if (mRewrapFlag) { + if( mRewrapFlag ) { // extract the data data = line.substring( - DRM_LDIF_PRIVATE_KEY_DATA.length() + 1).trim(); + DRM_LDIF_PRIVATE_KEY_DATA.length() + 1 + ).trim(); - while ((line = ldif_record.next()) != null) { - if (line.startsWith(SPACE)) { + while( ( line = ldif_record.next() ) != null ) { + if( line.startsWith( SPACE ) ) { data += line.trim(); } else { break; @@ -2967,36 +3908,49 @@ public class DRMTool { // Decode the ASCII BASE 64 certificate // enclosed in the String() object // into a BINARY BASE 64 byte[] object - source_wrappedKeyData = com.netscape.osutil.OSUtil - .AtoB(data); + source_wrappedKeyData = + com.netscape.osutil.OSUtil.AtoB( data ); // rewrap the source wrapped private key data - target_wrappedKeyData = rewrap_wrapped_key_data(source_wrappedKeyData); + target_wrappedKeyData = rewrap_wrapped_key_data( + source_wrappedKeyData ); // Encode the BINARY BASE 64 byte[] object // into an ASCII BASE 64 certificate // enclosed in a String() object - revised_data = com.netscape.osutil.OSUtil - .BtoA(target_wrappedKeyData); + revised_data = com.netscape.osutil.OSUtil.BtoA( + target_wrappedKeyData ); // Unformat the ASCII BASE 64 certificate // for the log file - unformatted_data = stripEOL(revised_data); + unformatted_data = stripEOL( revised_data ); // Format the ASCII BASE 64 certificate // to match the desired LDIF format formatted_data = format_ldif_data( - PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH, - unformatted_data); + PRIVATE_KEY_DATA_FIRST_LINE_DATA_LENGTH, + unformatted_data ); // construct a revised 'privateKeyData' line - output = DRM_LDIF_PRIVATE_KEY_DATA + SPACE - + formatted_data + NEWLINE + line; + output = DRM_LDIF_PRIVATE_KEY_DATA + + SPACE + + formatted_data + + NEWLINE + + line; // log this information - log("Changed 'privateKeyData' from:" + NEWLINE + TIC - + data + TIC + NEWLINE + " to:" + NEWLINE + TIC - + unformatted_data + TIC + NEWLINE, false); + log( "Changed 'privateKeyData' from:" + + NEWLINE + + TIC + + data + + TIC + + NEWLINE + + " to:" + + NEWLINE + + TIC + + unformatted_data + + TIC + + NEWLINE, false ); } else { output = line; } @@ -3004,191 +3958,229 @@ public class DRMTool { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_PRIVATE_KEY_DATA + "' for record type='" - + record_type + "'!" + NEWLINE, true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_PRIVATE_KEY_DATA + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } - } catch (Exception exRewrap) { - log("ERROR: Unable to rewrap BINARY BASE 64 data. " - + "Exception: '" + exRewrap.toString() + "'" + NEWLINE, - true); + } catch( Exception exRewrap ) { + log( "ERROR: Unable to rewrap BINARY BASE 64 data. " + + "Exception: '" + + exRewrap.toString() + + "'" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for DRM_LDIF_REQUEST_ID. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_request_id(String record_type, String line) { + private static String output_request_id( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { - if (drmtoolCfg.get(DRMTOOL_CFG_ENROLLMENT_REQUEST_ID)) { - output = compose_numeric_line(DRM_LDIF_REQUEST_ID, SPACE, line, - true); + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_ENROLLMENT_REQUEST_ID ) ) { + output = compose_numeric_line( DRM_LDIF_REQUEST_ID, + SPACE, + line, + true ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECOVERY)) { - if (drmtoolCfg.get(DRMTOOL_CFG_RECOVERY_REQUEST_ID)) { - output = compose_numeric_line(DRM_LDIF_REQUEST_ID, SPACE, line, - true); + } else if( record_type.equals( DRM_LDIF_RECOVERY ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_RECOVERY_REQUEST_ID ) ) { + output = compose_numeric_line( DRM_LDIF_REQUEST_ID, + SPACE, + line, + true ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_KEYGEN)) { - if (drmtoolCfg.get(DRMTOOL_CFG_KEYGEN_REQUEST_ID)) { - output = compose_numeric_line(DRM_LDIF_REQUEST_ID, SPACE, line, - true); + } else if( record_type.equals( DRM_LDIF_KEYGEN ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_KEYGEN_REQUEST_ID ) ) { + output = compose_numeric_line( DRM_LDIF_REQUEST_ID, + SPACE, + line, + true ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" + DRM_LDIF_REQUEST_ID - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_REQUEST_ID + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for DRM_LDIF_SERIAL_NO. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_serial_no(String record_type, String line) { + private static String output_serial_no( String record_type, + String line ) { String output = null; - if (record_type.equals(DRM_LDIF_CA_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO)) { - output = compose_numeric_line(DRM_LDIF_SERIAL_NO, SPACE, line, - true); + if( record_type.equals( DRM_LDIF_CA_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO ) ) { + output = compose_numeric_line( DRM_LDIF_SERIAL_NO, + SPACE, + line, + true ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_TPS_KEY_RECORD)) { - if (drmtoolCfg.get(DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO)) { - output = compose_numeric_line(DRM_LDIF_SERIAL_NO, SPACE, line, - true); + } else if( record_type.equals( DRM_LDIF_TPS_KEY_RECORD ) ) { + if( drmtoolCfg.get( DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO ) ) { + output = compose_numeric_line( DRM_LDIF_SERIAL_NO, + SPACE, + line, + true ); } else { output = line; } - } else if (record_type.equals(DRM_LDIF_RECORD)) { + } else if( record_type.equals( DRM_LDIF_RECORD ) ) { // Non-Request / Non-Key Record: - // Pass through the original - // 'serialno' line UNCHANGED - // so that it is ALWAYS written + // Pass through the original + // 'serialno' line UNCHANGED + // so that it is ALWAYS written output = line; } else { - log("ERROR: Mismatched record field='" + DRM_LDIF_SERIAL_NO - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_SERIAL_NO + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_AUTH_TOKEN_USER. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_extdata_auth_token_user(String record_type, - String line) { + private static String output_extdata_auth_token_user( String record_type, + String line ) { String data = null; String output = null; try { - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { // Since "-source_drm_naming_context", and // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this field if both of // these options have been selected - if (mDrmNamingContextsFlag) { - output = line.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = line.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } - } catch (NullPointerException exNullPointerException) { - log("ERROR: Unable to replace source DRM naming context '" - + mSourceDrmNamingContext - + "' with target DRM naming context '" - + mTargetDrmNamingContext + "' NullPointerException: '" - + exNullPointerException.toString() + "'" + NEWLINE, true); + } catch( NullPointerException exNullPointerException ) { + log( "ERROR: Unable to replace source DRM naming context '" + + mSourceDrmNamingContext + + "' with target DRM naming context '" + + mTargetDrmNamingContext + + "' NullPointerException: '" + + exNullPointerException.toString() + + "'" + + NEWLINE, true ); } return output; } + /** * Helper method which composes the output line for * DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN. *

- * + * * @param record_type the string representation of the input record type * @param line the string representation of the input line * @return the composed output line */ - private static String output_extdata_auth_token_user_dn(String record_type, - String line) { + private static String output_extdata_auth_token_user_dn( String record_type, + String line ) { String data = null; String output = null; try { - if (record_type.equals(DRM_LDIF_ENROLLMENT)) { + if( record_type.equals( DRM_LDIF_ENROLLMENT ) ) { // Since "-source_drm_naming_context", and // "-target_drm_naming_context" are OPTIONAL // parameters, ONLY process this field if both of // these options have been selected - if (mDrmNamingContextsFlag) { - output = line.replace(mSourceDrmNamingContext, - mTargetDrmNamingContext); + if( mDrmNamingContextsFlag ) { + output = line.replace( mSourceDrmNamingContext, + mTargetDrmNamingContext ); } else { output = line; } } else { - log("ERROR: Mismatched record field='" - + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN - + "' for record type='" + record_type + "'!" + NEWLINE, - true); + log( "ERROR: Mismatched record field='" + + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN + + "' for record type='" + + record_type + + "'!" + + NEWLINE, true ); } - } catch (NullPointerException exNullPointerException) { - log("ERROR: Unable to replace source DRM naming context '" - + mSourceDrmNamingContext - + "' with target DRM naming context '" - + mTargetDrmNamingContext + "' NullPointerException: '" - + exNullPointerException.toString() + "'" + NEWLINE, true); + } catch( NullPointerException exNullPointerException ) { + log( "ERROR: Unable to replace source DRM naming context '" + + mSourceDrmNamingContext + + "' with target DRM naming context '" + + mTargetDrmNamingContext + + "' NullPointerException: '" + + exNullPointerException.toString() + + "'" + + NEWLINE, true ); } return output; } + /** - * This method performs the actual parsing of the "source" LDIF file and - * produces the "target" LDIF file. + * This method performs the actual parsing of the "source" LDIF file + * and produces the "target" LDIF file. *

- * + * * @return true if the "target" LDIF file is successfully created */ private static boolean convert_source_ldif_to_target_ldif() { @@ -3202,72 +4194,80 @@ public class DRMTool { String data = null; String record_type = null; - if (mRewrapFlag) { + if( mRewrapFlag ) { success = obtain_RSA_rewrapping_keys(); - if (!success) { + if( !success ) { return FAILURE; } } // Create a vector for LDIF input - record = new Vector(INITIAL_LDIF_RECORD_CAPACITY); + record = new Vector( INITIAL_LDIF_RECORD_CAPACITY ); // Process each line in the source LDIF file // and store it in the target LDIF file try { // Open source LDIF file for reading - reader = new BufferedReader(new FileReader(mSourceLdifFilename)); + reader = new BufferedReader( + new FileReader( mSourceLdifFilename ) ); // Open target LDIF file for writing - writer = new PrintWriter(new BufferedWriter(new FileWriter( - mTargetLdifFilename))); + writer = new PrintWriter( + new BufferedWriter( + new FileWriter( mTargetLdifFilename ) ) ); - System.out.print("PROCESSING: "); - while ((input = reader.readLine()) != null) { + System.out.print( "PROCESSING: " ); + while( ( input = reader.readLine() ) != null ) { // Read in a record from the source LDIF file and // add this line of input into the record vector - success = record.add(input); - if (!success) { + success = record.add( input ); + if( !success ) { return FAILURE; } // Check for the end of an LDIF record - if (!input.equals("")) { + if( !input.equals( "" ) ) { // Check to see if input line identifies the record type - if (input.startsWith(DRM_LDIF_REQUEST_TYPE)) { + if( input.startsWith( DRM_LDIF_REQUEST_TYPE ) ) { // set the record type: // - // * DRM_LDIF_ENROLLMENT - // * DRM_LDIF_KEYGEN - // * DRM_LDIF_RECOVERY + // * DRM_LDIF_ENROLLMENT + // * DRM_LDIF_KEYGEN + // * DRM_LDIF_RECOVERY // record_type = input.substring( - DRM_LDIF_REQUEST_TYPE.length() + 1).trim(); - if (!record_type.equals(DRM_LDIF_ENROLLMENT) - && !record_type.equals(DRM_LDIF_KEYGEN) - && !record_type.equals(DRM_LDIF_RECOVERY)) { - log("ERROR: Unknown LDIF record type='" - + record_type + "'!" + NEWLINE, true); + DRM_LDIF_REQUEST_TYPE.length() + 1 + ).trim(); + if( !record_type.equals( DRM_LDIF_ENROLLMENT ) && + !record_type.equals( DRM_LDIF_KEYGEN ) && + !record_type.equals( DRM_LDIF_RECOVERY ) ) { + log( "ERROR: Unknown LDIF record type='" + + record_type + + "'!" + + NEWLINE, true ); return FAILURE; } - } else if (input.startsWith(DRM_LDIF_ARCHIVED_BY)) { + } else if( input.startsWith( DRM_LDIF_ARCHIVED_BY ) ) { // extract the data data = input.substring( - DRM_LDIF_ARCHIVED_BY.length() + 1).trim(); + DRM_LDIF_ARCHIVED_BY.length() + 1 + ).trim(); // set the record type: // - // * DRM_LDIF_CA_KEY_RECORD - // * DRM_LDIF_TPS_KEY_RECORD + // * DRM_LDIF_CA_KEY_RECORD + // * DRM_LDIF_TPS_KEY_RECORD // - if (data.startsWith(DRM_LDIF_TPS_KEY_RECORD)) { + if( data.startsWith( DRM_LDIF_TPS_KEY_RECORD ) ) { record_type = DRM_LDIF_TPS_KEY_RECORD; - } else if (data.startsWith(DRM_LDIF_CA_KEY_RECORD)) { + } else if( data.startsWith( DRM_LDIF_CA_KEY_RECORD ) ) { record_type = DRM_LDIF_CA_KEY_RECORD; } else { - log("ERROR: Unable to determine LDIF record type " - + "from data='" + data + "'!" + NEWLINE, - true); + log( "ERROR: Unable to determine LDIF record type " + + "from data='" + + data + + "'!" + + NEWLINE, true ); return FAILURE; } } @@ -3280,24 +4280,24 @@ public class DRMTool { // an LDIF request record nor an LDIF key record; check // to see if it needs to be written out to the target // LDIF file or thrown away. - if ((record_type == null) - && mProcessRequestsAndKeyRecordsOnlyFlag) { + if( ( record_type == null ) && + mProcessRequestsAndKeyRecordsOnlyFlag ) { // Mark each removed record with an 'x' - System.out.print("x"); + System.out.print( "x" ); // log this information - log("INFO: Throwing away an LDIF record which is " - + "neither a Request nor a Key Record!" + NEWLINE, - false); + log( "INFO: Throwing away an LDIF record which is " + + "neither a Request nor a Key Record!" + + NEWLINE, false ); // clear this LDIF record from the record vector record.clear(); - // NOTE: there is no need to reset the record type + // NOTE: there is no need to reset the record type // begin adding input lines into a new record continue; - } else if (record_type == null) { + } else if( record_type == null ) { // Set record type to specify a "generic" LDIF record record_type = DRM_LDIF_RECORD; } @@ -3305,92 +4305,98 @@ public class DRMTool { ldif_record = record.iterator(); // Process each line of the record: - // * If LDIF Record Type for this line is 'valid' - // * If DRMTOOL Configuration File Parameter is 'true' - // * Process this data - // * Else If DRMTOOL Configuration File Parameter is 'false' - // * Pass through this data unchanged - // * Else If LDIF Record Type for this line is 'invalid' - // * Log error and leave method returning 'false' - while (ldif_record.hasNext()) { + // * If LDIF Record Type for this line is 'valid' + // * If DRMTOOL Configuration File Parameter is 'true' + // * Process this data + // * Else If DRMTOOL Configuration File Parameter is 'false' + // * Pass through this data unchanged + // * Else If LDIF Record Type for this line is 'invalid' + // * Log error and leave method returning 'false' + while( ldif_record.hasNext() ) { line = ldif_record.next(); - if (line.startsWith(DRM_LDIF_CN)) { - output = output_cn(record_type, line); - if (output == null) { + if( line.startsWith( DRM_LDIF_CN ) ) { + output = output_cn( record_type, line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_DATE_OF_MODIFY)) { - output = output_date_of_modify(record_type, line); - if (output == null) { + } else if( line.startsWith( DRM_LDIF_DATE_OF_MODIFY ) ) { + output = output_date_of_modify( record_type, line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_DN)) { - output = output_dn(record_type, line); - if (output == null) { + } else if( line.startsWith( DRM_LDIF_DN ) ) { + output = output_dn( record_type, line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_EXTDATA_KEY_RECORD)) { - output = output_extdata_key_record(record_type, line); - if (output == null) { + } else if(line.startsWith( DRM_LDIF_EXTDATA_KEY_RECORD )) { + output = output_extdata_key_record( record_type, + line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_EXTDATA_REQUEST_ID)) { - output = output_extdata_request_id(record_type, line); - if (output == null) { + } else if(line.startsWith( DRM_LDIF_EXTDATA_REQUEST_ID )) { + output = output_extdata_request_id( record_type, + line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) { - output = output_extdata_request_notes(record_type, line); - if (output == null) { + } else if(line.startsWith(DRM_LDIF_EXTDATA_REQUEST_NOTES)) { + output = output_extdata_request_notes( record_type, + line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_EXTDATA_REQUEST_TYPE)) { + } else if(line.startsWith(DRM_LDIF_EXTDATA_REQUEST_TYPE)) { // if one is not already present, // compose and write out the missing // 'extdata_requestnotes' line - create_extdata_request_notes(record_type, - previous_line, writer); + create_extdata_request_notes( record_type, + previous_line, + writer ); // ALWAYS pass through the original // 'extdata-requesttype' line UNCHANGED // so that it is ALWAYS written output = line; - } else if (line.startsWith(DRM_LDIF_EXTDATA_SERIAL_NUMBER)) { - output = output_extdata_serial_number(record_type, line); - if (output == null) { + } else if(line.startsWith(DRM_LDIF_EXTDATA_SERIAL_NUMBER)) { + output = output_extdata_serial_number( record_type, + line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_PRIVATE_KEY_DATA)) { - output = output_private_key_data(record_type, line); - if (output == null) { + } else if( line.startsWith( DRM_LDIF_PRIVATE_KEY_DATA ) ) { + output = output_private_key_data( record_type, + line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_REQUEST_ID)) { - output = output_request_id(record_type, line); - if (output == null) { + } else if( line.startsWith( DRM_LDIF_REQUEST_ID ) ) { + output = output_request_id( record_type, line ); + if( output == null ) { return FAILURE; } - } else if (line.startsWith(DRM_LDIF_SERIAL_NO)) { - output = output_serial_no(record_type, line); - if (output == null) { + } else if( line.startsWith( DRM_LDIF_SERIAL_NO ) ) { + output = output_serial_no( record_type, line ); + if( output == null ) { return FAILURE; } - } else if (previous_line != null - && previous_line - .startsWith(DRM_LDIF_EXTDATA_AUTH_TOKEN_USER)) { - output = output_extdata_auth_token_user(record_type, - line); - if (output == null) { + } else if( previous_line != null && + previous_line.startsWith( + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER ) ) { + output = output_extdata_auth_token_user( record_type, + line ); + if( output == null ) { return FAILURE; } - } else if (previous_line != null - && previous_line - .startsWith(DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN)) { - output = output_extdata_auth_token_user_dn(record_type, - line); - if (output == null) { + } else if( previous_line != null && + previous_line.startsWith( + DRM_LDIF_EXTDATA_AUTH_TOKEN_USER_DN ) ) { + output = output_extdata_auth_token_user_dn( record_type, + line ); + if( output == null ) { return FAILURE; } } else { @@ -3402,36 +4408,42 @@ public class DRMTool { previous_line = output; // Always write out the output line and flush the buffer - writer.write(output + NEWLINE); + writer.write( output + NEWLINE ); writer.flush(); - System.out.print("."); + System.out.print( "." ); } // Mark the end of the LDIF record - System.out.print("!"); + System.out.print( "!" ); // clear this LDIF record from the record vector record.clear(); } - System.out.println(" FINISHED." + NEWLINE); - } catch (IOException exIO) { - log("ERROR: line='" + line + "' OR output='" + output - + "' IOException: '" + exIO.toString() + "'" + NEWLINE, - true); + System.out.println( " FINISHED." + NEWLINE ); + } catch( IOException exIO ) { + log( "ERROR: line='" + + line + + "' OR output='" + + output + + "' IOException: '" + + exIO.toString() + + "'" + + NEWLINE, true ); return FAILURE; } return SUCCESS; } + /**************************************/ /* DRMTOOL Config File Parser Methods */ /**************************************/ /** - * This method performs the actual parsing of the DRMTOOL config file and - * initializes how the DRM Record Fields should be processed. + * This method performs the actual parsing of the DRMTOOL config file + * and initializes how the DRM Record Fields should be processed. *

- * + * * @return true if the DRMTOOL config file is successfully processed */ private static boolean process_drmtool_config_file() { @@ -3446,83 +4458,95 @@ public class DRMTool { // in the DRMTOOL config file try { // Open DRMTOOL config file for reading - reader = new BufferedReader(new FileReader(mDrmtoolCfgFilename)); + reader = new BufferedReader( + new FileReader( mDrmtoolCfgFilename ) ); // Create a hashtable for relevant name/value pairs drmtoolCfg = new Hashtable(); - System.out.print("PROCESSING DRMTOOL CONFIG FILE: "); - while ((line = reader.readLine()) != null) { - if (line.startsWith(DRMTOOL_CFG_PREFIX)) { + System.out.print( "PROCESSING DRMTOOL CONFIG FILE: " ); + while( ( line = reader.readLine() ) != null ) { + if( line.startsWith( DRMTOOL_CFG_PREFIX ) ) { // obtain "name=value" pair - name_value_pair = line.split(EQUAL_SIGN); + name_value_pair = line.split( EQUAL_SIGN ); // obtain "name" name = name_value_pair[0]; // compute "boolean" value - if (name_value_pair[1].equals("true")) { + if( name_value_pair[1].equals( "true" ) ) { value = Boolean.TRUE; } else { value = Boolean.FALSE; } // store relevant DRM LDIF fields for processing - if (name.equals(DRMTOOL_CFG_ENROLLMENT_CN) - || name.equals(DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY) - || name.equals(DRMTOOL_CFG_ENROLLMENT_DN) - || name.equals(DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD) - || name.equals(DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES) - || name.equals(DRMTOOL_CFG_ENROLLMENT_REQUEST_ID) - || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_CN) - || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY) - || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_DN) - || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA) - || name.equals(DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO) - || name.equals(DRMTOOL_CFG_RECOVERY_CN) - || name.equals(DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY) - || name.equals(DRMTOOL_CFG_RECOVERY_DN) - || name.equals(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID) - || name.equals(DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES) - || name.equals(DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER) - || name.equals(DRMTOOL_CFG_RECOVERY_REQUEST_ID) - || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_CN) - || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY) - || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_DN) - || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA) - || name.equals(DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO) - || name.equals(DRMTOOL_CFG_KEYGEN_CN) - || name.equals(DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY) - || name.equals(DRMTOOL_CFG_KEYGEN_DN) - || name.equals(DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD) - || name.equals(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID) - || name.equals(DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES) - || name.equals(DRMTOOL_CFG_KEYGEN_REQUEST_ID)) { - drmtoolCfg.put(name, value); - System.out.print("."); + if( name.equals( DRMTOOL_CFG_ENROLLMENT_CN ) + || name.equals( DRMTOOL_CFG_ENROLLMENT_DATE_OF_MODIFY ) + || name.equals( DRMTOOL_CFG_ENROLLMENT_DN ) + || name.equals( DRMTOOL_CFG_ENROLLMENT_EXTDATA_KEY_RECORD ) + || name.equals( DRMTOOL_CFG_ENROLLMENT_EXTDATA_REQUEST_NOTES ) + || name.equals( DRMTOOL_CFG_ENROLLMENT_REQUEST_ID ) + || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_CN ) + || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_DATE_OF_MODIFY ) + || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_DN ) + || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_PRIVATE_KEY_DATA ) + || name.equals( DRMTOOL_CFG_CA_KEY_RECORD_SERIAL_NO ) + || name.equals( DRMTOOL_CFG_RECOVERY_CN ) + || name.equals( DRMTOOL_CFG_RECOVERY_DATE_OF_MODIFY ) + || name.equals( DRMTOOL_CFG_RECOVERY_DN ) + || name.equals( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_ID ) + || name.equals( DRMTOOL_CFG_RECOVERY_EXTDATA_REQUEST_NOTES ) + || name.equals( DRMTOOL_CFG_RECOVERY_EXTDATA_SERIAL_NUMBER ) + || name.equals( DRMTOOL_CFG_RECOVERY_REQUEST_ID ) + || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_CN ) + || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_DATE_OF_MODIFY ) + || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_DN ) + || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_PRIVATE_KEY_DATA ) + || name.equals( DRMTOOL_CFG_TPS_KEY_RECORD_SERIAL_NO ) + || name.equals( DRMTOOL_CFG_KEYGEN_CN ) + || name.equals( DRMTOOL_CFG_KEYGEN_DATE_OF_MODIFY ) + || name.equals( DRMTOOL_CFG_KEYGEN_DN ) + || name.equals( DRMTOOL_CFG_KEYGEN_EXTDATA_KEY_RECORD ) + || name.equals( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_ID ) + || name.equals( DRMTOOL_CFG_KEYGEN_EXTDATA_REQUEST_NOTES ) + || name.equals( DRMTOOL_CFG_KEYGEN_REQUEST_ID ) ) { + drmtoolCfg.put( name, value ); + System.out.print( "." ); } } } - System.out.println(" FINISHED." + NEWLINE); - } catch (FileNotFoundException exDrmtoolCfgFileNotFound) { - log("ERROR: No DRMTOOL config file named '" + mDrmtoolCfgFilename - + "' exists! FileNotFoundException: '" - + exDrmtoolCfgFileNotFound.toString() + "'" + NEWLINE, true); + System.out.println( " FINISHED." + NEWLINE ); + } catch( FileNotFoundException exDrmtoolCfgFileNotFound ) { + log( "ERROR: No DRMTOOL config file named '" + + mDrmtoolCfgFilename + + "' exists! FileNotFoundException: '" + + exDrmtoolCfgFileNotFound.toString() + + "'" + + NEWLINE, true ); return FAILURE; - } catch (IOException exDrmtoolCfgIO) { - log("ERROR: line='" + line + "' IOException: '" - + exDrmtoolCfgIO.toString() + "'" + NEWLINE, true); + } catch( IOException exDrmtoolCfgIO ) { + log( "ERROR: line='" + + line + + "' IOException: '" + + exDrmtoolCfgIO.toString() + + "'" + + NEWLINE, true ); return FAILURE; - } catch (PatternSyntaxException exDrmtoolCfgNameValuePattern) { - log("ERROR: line='" + line + "' PatternSyntaxException: '" - + exDrmtoolCfgNameValuePattern.toString() + "'" + NEWLINE, - true); + } catch( PatternSyntaxException exDrmtoolCfgNameValuePattern ) { + log( "ERROR: line='" + + line + + "' PatternSyntaxException: '" + + exDrmtoolCfgNameValuePattern.toString() + + "'" + + NEWLINE, true ); return FAILURE; } return SUCCESS; } + /************/ /* DRM Tool */ /************/ @@ -3530,10 +4554,10 @@ public class DRMTool { /** * The main DRMTool method. *

- * + * * @param args DRMTool options */ - public static void main(String[] args) { + public static void main( String[] args ) { // Variables String append_id_offset = null; String remove_id_offset = null; @@ -3550,141 +4574,155 @@ public class DRMTool { boolean success = false; // Get current date and time - mDateOfModify = now(DATE_OF_MODIFY_PATTERN); + mDateOfModify = now( DATE_OF_MODIFY_PATTERN ); // Check that the correct number of arguments were // submitted to the program - if ((args.length != ID_OFFSET_ARGS) - && (args.length != (ID_OFFSET_ARGS + 1)) - && (args.length != (ID_OFFSET_ARGS + 4)) - && (args.length != (ID_OFFSET_ARGS + 5)) - && (args.length != REWRAP_ARGS) - && (args.length != (REWRAP_ARGS + 1)) - && (args.length != (REWRAP_ARGS + 2)) - && (args.length != (REWRAP_ARGS + 3)) - && (args.length != (REWRAP_ARGS + 4)) - && (args.length != (REWRAP_ARGS + 5)) - && (args.length != (REWRAP_ARGS + 6)) - && (args.length != (REWRAP_ARGS + 7)) - && (args.length != REWRAP_AND_ID_OFFSET_ARGS) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 1)) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 2)) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 3)) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 4)) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 5)) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 6)) - && (args.length != (REWRAP_AND_ID_OFFSET_ARGS + 7))) { - System.err.println("ERROR: Incorrect number of arguments!" - + NEWLINE); + if( ( args.length != ID_OFFSET_ARGS ) && + ( args.length != ( ID_OFFSET_ARGS + 1 ) ) && + ( args.length != ( ID_OFFSET_ARGS + 4 ) ) && + ( args.length != ( ID_OFFSET_ARGS + 5 ) ) && + ( args.length != REWRAP_ARGS ) && + ( args.length != ( REWRAP_ARGS + 1 ) ) && + ( args.length != ( REWRAP_ARGS + 2 ) ) && + ( args.length != ( REWRAP_ARGS + 3 ) ) && + ( args.length != ( REWRAP_ARGS + 4 ) ) && + ( args.length != ( REWRAP_ARGS + 5 ) ) && + ( args.length != ( REWRAP_ARGS + 6 ) ) && + ( args.length != ( REWRAP_ARGS + 7 ) ) && + ( args.length != REWRAP_AND_ID_OFFSET_ARGS ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 1 ) ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 2 ) ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 3 ) ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 4 ) ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 5 ) ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 6 ) ) && + ( args.length != ( REWRAP_AND_ID_OFFSET_ARGS + 7 ) ) ) { + System.err.println( "ERROR: Incorrect number of arguments!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Process command-line arguments - for (int i = 0; i < args.length; i += 2) { - if (args[i].equals(DRMTOOL_CFG_FILE)) { + for( int i = 0; i < args.length; i += 2 ) { + if( args[i].equals( DRMTOOL_CFG_FILE ) ) { mDrmtoolCfgFilename = args[i + 1]; mMandatoryNameValuePairs++; - } else if (args[i].equals(SOURCE_LDIF_FILE)) { + } else if( args[i].equals( SOURCE_LDIF_FILE ) ) { mSourceLdifFilename = args[i + 1]; mMandatoryNameValuePairs++; - } else if (args[i].equals(TARGET_LDIF_FILE)) { + } else if( args[i].equals( TARGET_LDIF_FILE ) ) { mTargetLdifFilename = args[i + 1]; mMandatoryNameValuePairs++; - } else if (args[i].equals(LOG_FILE)) { + } else if( args[i].equals( LOG_FILE ) ) { mLogFilename = args[i + 1]; mMandatoryNameValuePairs++; - } else if (args[i].equals(SOURCE_NSS_DB_PATH)) { + } else if( args[i].equals( SOURCE_NSS_DB_PATH ) ) { mSourcePKISecurityDatabasePath = args[i + 1]; mRewrapNameValuePairs++; - } else if (args[i].equals(SOURCE_STORAGE_TOKEN_NAME)) { + } else if( args[i].equals( SOURCE_STORAGE_TOKEN_NAME ) ) { mSourceStorageTokenName = args[i + 1]; mRewrapNameValuePairs++; - } else if (args[i].equals(SOURCE_STORAGE_CERT_NICKNAME)) { + } else if( args[i].equals( SOURCE_STORAGE_CERT_NICKNAME ) ) { mSourceStorageCertNickname = args[i + 1]; mRewrapNameValuePairs++; - } else if (args[i].equals(TARGET_STORAGE_CERTIFICATE_FILE)) { + } else if( args[i].equals( TARGET_STORAGE_CERTIFICATE_FILE ) ) { mTargetStorageCertificateFilename = args[i + 1]; mRewrapNameValuePairs++; - } else if (args[i].equals(SOURCE_NSS_DB_PWDFILE)) { + } else if( args[i].equals( SOURCE_NSS_DB_PWDFILE ) ) { mSourcePKISecurityDatabasePwdfile = args[i + 1]; mPKISecurityDatabasePwdfileNameValuePairs++; - } else if (args[i].equals(APPEND_ID_OFFSET)) { + } else if( args[i].equals( APPEND_ID_OFFSET ) ) { append_id_offset = args[i + 1]; mAppendIdOffsetNameValuePairs++; - } else if (args[i].equals(REMOVE_ID_OFFSET)) { + } else if( args[i].equals( REMOVE_ID_OFFSET ) ) { remove_id_offset = args[i + 1]; mRemoveIdOffsetNameValuePairs++; - } else if (args[i].equals(SOURCE_DRM_NAMING_CONTEXT)) { + } else if( args[i].equals( SOURCE_DRM_NAMING_CONTEXT ) ) { mSourceDrmNamingContext = args[i + 1]; mDrmNamingContextNameValuePairs++; - } else if (args[i].equals(TARGET_DRM_NAMING_CONTEXT)) { + } else if( args[i].equals( TARGET_DRM_NAMING_CONTEXT ) ) { mTargetDrmNamingContext = args[i + 1]; mDrmNamingContextNameValuePairs++; - } else if (args[i].equals(PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY)) { + } else if( args[i].equals( PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY ) ) + { mProcessRequestsAndKeyRecordsOnlyFlag = true; i -= 1; } else { - System.err.println("ERROR: Unknown argument '" + args[i] - + "'!" + NEWLINE); + System.err.println( "ERROR: Unknown argument '" + + args[i] + + "'!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } } // Verify that correct number of valid mandatory // arguments were submitted to the program - if (mMandatoryNameValuePairs != MANDATORY_NAME_VALUE_PAIRS - || mDrmtoolCfgFilename == null - || mDrmtoolCfgFilename.length() == 0 - || mSourceLdifFilename == null - || mSourceLdifFilename.length() == 0 - || mTargetLdifFilename == null - || mTargetLdifFilename.length() == 0 || mLogFilename == null - || mLogFilename.length() == 0) { - System.err - .println("ERROR: Missing mandatory arguments!" + NEWLINE); + if( mMandatoryNameValuePairs != MANDATORY_NAME_VALUE_PAIRS || + mDrmtoolCfgFilename == null || + mDrmtoolCfgFilename.length() == 0 || + mSourceLdifFilename == null || + mSourceLdifFilename.length() == 0 || + mTargetLdifFilename == null || + mTargetLdifFilename.length() == 0 || + mLogFilename == null || + mLogFilename.length() == 0 ) { + System.err.println( "ERROR: Missing mandatory arguments!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } else { // Check for a valid DRMTOOL config file - cfgFile = new File(mDrmtoolCfgFilename); - if (!cfgFile.exists() || !cfgFile.isFile() - || (cfgFile.length() == 0)) { - System.err.println("ERROR: '" + mDrmtoolCfgFilename - + "' does NOT exist, is NOT a file, " + "or is empty!" - + NEWLINE); + cfgFile = new File( mDrmtoolCfgFilename ); + if( !cfgFile.exists() || + !cfgFile.isFile() || + ( cfgFile.length() == 0 ) ) { + System.err.println( "ERROR: '" + + mDrmtoolCfgFilename + + "' does NOT exist, is NOT a file, " + + "or is empty!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Check for a valid source LDIF file - sourceFile = new File(mSourceLdifFilename); - if (!sourceFile.exists() || !sourceFile.isFile() - || (sourceFile.length() == 0)) { - System.err.println("ERROR: '" + mSourceLdifFilename - + "' does NOT exist, is NOT a file, " + "or is empty!" - + NEWLINE); + sourceFile = new File( mSourceLdifFilename ); + if( !sourceFile.exists() || + !sourceFile.isFile() || + ( sourceFile.length() == 0 ) ) { + System.err.println( "ERROR: '" + + mSourceLdifFilename + + "' does NOT exist, is NOT a file, " + + "or is empty!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Check that the target LDIF file does NOT exist - targetFile = new File(mTargetLdifFilename); - if (targetFile.exists()) { - System.err.println("ERROR: '" + mTargetLdifFilename - + "' ALREADY exists!" + NEWLINE); + targetFile = new File( mTargetLdifFilename ); + if( targetFile.exists() ) { + System.err.println( "ERROR: '" + + mTargetLdifFilename + + "' ALREADY exists!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Check that the log file does NOT exist - logFile = new File(mLogFilename); - if (logFile.exists()) { - System.err.println("ERROR: '" + mLogFilename - + "' ALREADY exists!" + NEWLINE); + logFile = new File( mLogFilename ); + if( logFile.exists() ) { + System.err.println( "ERROR: '" + + mLogFilename + + "' ALREADY exists!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Mark the 'Mandatory' flag true @@ -3693,44 +4731,47 @@ public class DRMTool { // Check to see that if the 'Rewrap' command-line options were // specified, that they are all present and accounted for - if (mRewrapNameValuePairs > 0) { - if (mRewrapNameValuePairs != REWRAP_NAME_VALUE_PAIRS - || mSourcePKISecurityDatabasePath == null - || mSourcePKISecurityDatabasePath.length() == 0 - || mSourceStorageTokenName == null - || mSourceStorageTokenName.length() == 0 - || mSourceStorageCertNickname == null - || mSourceStorageCertNickname.length() == 0 - || mTargetStorageCertificateFilename == null - || mTargetStorageCertificateFilename.length() == 0) { - System.err.println("ERROR: Missing 'Rewrap' arguments!" - + NEWLINE); + if( mRewrapNameValuePairs > 0 ) { + if( mRewrapNameValuePairs != REWRAP_NAME_VALUE_PAIRS || + mSourcePKISecurityDatabasePath == null || + mSourcePKISecurityDatabasePath.length() == 0 || + mSourceStorageTokenName == null || + mSourceStorageTokenName.length() == 0 || + mSourceStorageCertNickname == null || + mSourceStorageCertNickname.length() == 0 || + mTargetStorageCertificateFilename == null || + mTargetStorageCertificateFilename.length() == 0 ) { + System.err.println( "ERROR: Missing 'Rewrap' arguments!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } else { // Check for a valid path to the PKI security databases - sourceDBPath = new File(mSourcePKISecurityDatabasePath); - if (!sourceDBPath.exists() || !sourceDBPath.isDirectory()) { - System.err.println("ERROR: '" - + mSourcePKISecurityDatabasePath - + "' does NOT exist or " + "'is NOT a directory!" - + NEWLINE); + sourceDBPath = new File( mSourcePKISecurityDatabasePath ); + if( !sourceDBPath.exists() || + !sourceDBPath.isDirectory() ) { + System.err.println( "ERROR: '" + + mSourcePKISecurityDatabasePath + + "' does NOT exist or " + + "'is NOT a directory!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Check for a valid target storage certificate file targetStorageCertFile = new File( - mTargetStorageCertificateFilename); - if (!targetStorageCertFile.exists() - || !targetStorageCertFile.isFile() - || (targetStorageCertFile.length() == 0)) { - System.err.println("ERROR: '" - + mTargetStorageCertificateFilename - + "' does NOT exist, is NOT a file, " - + "or is empty!" + NEWLINE); + mTargetStorageCertificateFilename ); + if( !targetStorageCertFile.exists() || + !targetStorageCertFile.isFile() || + ( targetStorageCertFile.length() == 0 ) ) { + System.err.println( "ERROR: '" + + mTargetStorageCertificateFilename + + "' does NOT exist, is NOT a file, " + + "or is empty!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Mark the 'Rewrap' flag true @@ -3741,135 +4782,165 @@ public class DRMTool { // Check to see that BOTH append 'ID Offset' command-line options // and remove 'ID Offset' command-line options were NOT specified // since these two command-line options are mutually exclusive! - if ((mAppendIdOffsetNameValuePairs > 0) - && (mRemoveIdOffsetNameValuePairs > 0)) { - System.err.println("ERROR: The 'append ID Offset' option " - + "and the 'remove ID Offset' option are " - + "mutually exclusive!" + NEWLINE); - printUsage(); - System.exit(0); + if( ( mAppendIdOffsetNameValuePairs > 0 ) && + ( mRemoveIdOffsetNameValuePairs > 0 ) ) { + System.err.println( "ERROR: The 'append ID Offset' option " + + "and the 'remove ID Offset' option are " + + "mutually exclusive!" + + NEWLINE ); + printUsage(); + System.exit( 0 ); } // Check to see that if the 'append ID Offset' command-line options // were specified, that they are all present and accounted for - if (mAppendIdOffsetNameValuePairs > 0) { - if (mAppendIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS - && append_id_offset != null - && append_id_offset.length() != 0) { + if( mAppendIdOffsetNameValuePairs > 0 ) { + if( mAppendIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS && + append_id_offset != null && + append_id_offset.length() != 0 ) { try { - if (!append_id_offset.matches("[0-9]++")) { - System.err.println("ERROR: '" + append_id_offset - + "' contains non-numeric " + "characters!" - + NEWLINE); + if( !append_id_offset.matches( "[0-9]++" ) ) { + System.err.println( "ERROR: '" + + append_id_offset + + "' contains non-numeric " + + "characters!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } else { - mAppendIdOffset = new BigInteger(append_id_offset); + mAppendIdOffset = new BigInteger( + append_id_offset ); // Mark the 'append ID Offset' flag true mAppendIdOffsetFlag = true; } - } catch (PatternSyntaxException exAppendPattern) { - System.err.println("ERROR: append_id_offset='" - + append_id_offset + "' PatternSyntaxException: '" - + exAppendPattern.toString() + "'" + NEWLINE); - System.exit(0); + } catch( PatternSyntaxException exAppendPattern ) { + System.err.println( "ERROR: append_id_offset='" + + append_id_offset + + "' PatternSyntaxException: '" + + exAppendPattern.toString() + + "'" + + NEWLINE ); + System.exit( 0 ); } } else { - System.err.println("ERROR: Missing " - + "'append ID Offset' arguments!" + NEWLINE); + System.err.println( "ERROR: Missing " + + "'append ID Offset' arguments!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } } // Check to see that if the 'remove ID Offset' command-line options // were specified, that they are all present and accounted for - if (mRemoveIdOffsetNameValuePairs > 0) { - if (mRemoveIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS - && remove_id_offset != null - && remove_id_offset.length() != 0) { + if( mRemoveIdOffsetNameValuePairs > 0 ) { + if( mRemoveIdOffsetNameValuePairs == ID_OFFSET_NAME_VALUE_PAIRS && + remove_id_offset != null && + remove_id_offset.length() != 0 ) { try { - if (!remove_id_offset.matches("[0-9]++")) { - System.err.println("ERROR: '" + remove_id_offset - + "' contains non-numeric " + "characters!" - + NEWLINE); + if( !remove_id_offset.matches( "[0-9]++" ) ) { + System.err.println( "ERROR: '" + + remove_id_offset + + "' contains non-numeric " + + "characters!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } else { - mRemoveIdOffset = new BigInteger(remove_id_offset); + mRemoveIdOffset = new BigInteger( + remove_id_offset ); // Mark the 'remove ID Offset' flag true mRemoveIdOffsetFlag = true; } - } catch (PatternSyntaxException exRemovePattern) { - System.err.println("ERROR: remove_id_offset='" - + remove_id_offset + "' PatternSyntaxException: '" - + exRemovePattern.toString() + "'" + NEWLINE); - System.exit(0); + } catch( PatternSyntaxException exRemovePattern ) { + System.err.println( "ERROR: remove_id_offset='" + + remove_id_offset + + "' PatternSyntaxException: '" + + exRemovePattern.toString() + + "'" + + NEWLINE ); + System.exit( 0 ); } } else { - System.err.println("ERROR: Missing " - + "'remove ID Offset' arguments!" + NEWLINE); + System.err.println( "ERROR: Missing " + + "'remove ID Offset' arguments!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } } // Make certain that at least one of the "Rewrap", "Append ID Offset", // or "Remove ID Offset" options has been specified - if (!mRewrapFlag && !mAppendIdOffsetFlag && !mRemoveIdOffsetFlag) { - System.err.println("ERROR: At least one of the 'rewrap', " - + "'append ID Offset', or 'remove ID Offset' " - + "options MUST be specified!" + NEWLINE); + if( !mRewrapFlag && + !mAppendIdOffsetFlag && + !mRemoveIdOffsetFlag ) { + System.err.println( "ERROR: At least one of the 'rewrap', " + + "'append ID Offset', or 'remove ID Offset' " + + "options MUST be specified!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } // Check to see that if the OPTIONAL // 'PKI Security Database Password File' // command-line options were specified, // that they are all present and accounted for - if (mPKISecurityDatabasePwdfileNameValuePairs > 0) { - if (mPKISecurityDatabasePwdfileNameValuePairs != PWDFILE_NAME_VALUE_PAIRS - || mSourcePKISecurityDatabasePwdfile == null - || mSourcePKISecurityDatabasePwdfile.length() == 0) { - System.err.println("ERROR: Missing 'Password File' " - + "arguments!" + NEWLINE); + if( mPKISecurityDatabasePwdfileNameValuePairs > 0 ) { + if( mPKISecurityDatabasePwdfileNameValuePairs != + PWDFILE_NAME_VALUE_PAIRS || + mSourcePKISecurityDatabasePwdfile == null || + mSourcePKISecurityDatabasePwdfile.length() == 0 ) { + System.err.println( "ERROR: Missing 'Password File' " + + "arguments!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } else { - if (mRewrapFlag) { + if( mRewrapFlag ) { // Check for a valid source PKI // security database password file - sourceDBPwdfile = new File( - mSourcePKISecurityDatabasePwdfile); - if (!sourceDBPwdfile.exists() || !sourceDBPwdfile.isFile() - || (sourceDBPwdfile.length() == 0)) { - System.err.println("ERROR: '" - + mSourcePKISecurityDatabasePwdfile - + "' does NOT exist, is NOT a file, " - + "or is empty!" + NEWLINE); + sourceDBPwdfile = new + File( mSourcePKISecurityDatabasePwdfile ); + if( !sourceDBPwdfile.exists() || + !sourceDBPwdfile.isFile() || + ( sourceDBPwdfile.length() == 0 ) ) { + System.err.println( "ERROR: '" + + mSourcePKISecurityDatabasePwdfile + + "' does NOT exist, is NOT a file, " + + "or is empty!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } use_PKI_security_database_pwdfile = SPACE - + SOURCE_NSS_DB_PWDFILE + SPACE + TIC - + mSourcePKISecurityDatabasePwdfile + TIC; + + SOURCE_NSS_DB_PWDFILE + + SPACE + + TIC + + mSourcePKISecurityDatabasePwdfile + + TIC; - mSourcePKISecurityDatabasePwdfileMessage = SPACE + PLUS - + SPACE + DRM_LDIF_USED_PWDFILE_MESSAGE; + mSourcePKISecurityDatabasePwdfileMessage = SPACE + + PLUS + + SPACE + + DRM_LDIF_USED_PWDFILE_MESSAGE; // Mark the 'Password File' flag true mPwdfileFlag = true; } else { - System.err.println("ERROR: The " + TIC - + SOURCE_NSS_DB_PWDFILE + TIC - + " option is ONLY valid when " - + "performing rewrapping." + NEWLINE); + System.err.println( "ERROR: The " + + TIC + + SOURCE_NSS_DB_PWDFILE + + TIC + + " option is ONLY valid when " + + "performing rewrapping." + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } } } else { @@ -3879,29 +4950,41 @@ public class DRMTool { // Check to see that if the OPTIONAL 'DRM Naming Context' command-line // options were specified, that they are all present and accounted for - if (mDrmNamingContextNameValuePairs > 0) { - if (mDrmNamingContextNameValuePairs != NAMING_CONTEXT_NAME_VALUE_PAIRS - || mSourceDrmNamingContext == null - || mSourceDrmNamingContext.length() == 0 - || mTargetDrmNamingContext == null - || mTargetDrmNamingContext.length() == 0) { - System.err.println("ERROR: Both 'source DRM naming context' " - + "and 'target DRM naming context' " - + "options MUST be specified!" + NEWLINE); + if( mDrmNamingContextNameValuePairs > 0 ) { + if( mDrmNamingContextNameValuePairs != + NAMING_CONTEXT_NAME_VALUE_PAIRS || + mSourceDrmNamingContext == null || + mSourceDrmNamingContext.length() == 0 || + mTargetDrmNamingContext == null || + mTargetDrmNamingContext.length() == 0 ) { + System.err.println( "ERROR: Both 'source DRM naming context' " + + "and 'target DRM naming context' " + + "options MUST be specified!" + + NEWLINE ); printUsage(); - System.exit(0); + System.exit( 0 ); } else { process_drm_naming_context_fields = SPACE - + SOURCE_DRM_NAMING_CONTEXT + SPACE + TIC - + mSourceDrmNamingContext + TIC + SPACE - + TARGET_DRM_NAMING_CONTEXT + SPACE + TIC - + mTargetDrmNamingContext + TIC; - - mDrmNamingContextMessage = SPACE + PLUS + SPACE - + DRM_LDIF_SOURCE_NAME_CONTEXT_MESSAGE - + mSourceDrmNamingContext - + DRM_LDIF_TARGET_NAME_CONTEXT_MESSAGE - + mTargetDrmNamingContext + TIC; + + SOURCE_DRM_NAMING_CONTEXT + + SPACE + + TIC + + mSourceDrmNamingContext + + TIC + + SPACE + + TARGET_DRM_NAMING_CONTEXT + + SPACE + + TIC + + mTargetDrmNamingContext + + TIC; + + mDrmNamingContextMessage = SPACE + + PLUS + + SPACE + + DRM_LDIF_SOURCE_NAME_CONTEXT_MESSAGE + + mSourceDrmNamingContext + + DRM_LDIF_TARGET_NAME_CONTEXT_MESSAGE + + mTargetDrmNamingContext + + TIC; // Mark the 'DRM Naming Contexts' flag true mDrmNamingContextsFlag = true; @@ -3912,186 +4995,268 @@ public class DRMTool { } // Check for OPTIONAL "Process Requests and Key Records ONLY" option - if (mProcessRequestsAndKeyRecordsOnlyFlag) { + if( mProcessRequestsAndKeyRecordsOnlyFlag ) { process_requests_and_key_records_only = SPACE - + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY; - mProcessRequestsAndKeyRecordsOnlyMessage = SPACE + PLUS + SPACE - + DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE; + + PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY; + mProcessRequestsAndKeyRecordsOnlyMessage = SPACE + PLUS + SPACE + + DRM_LDIF_PROCESS_REQUESTS_AND_KEY_RECORDS_ONLY_MESSAGE; } else { process_requests_and_key_records_only = ""; mProcessRequestsAndKeyRecordsOnlyMessage = ""; } // Enable logging process . . . - open_log(mLogFilename); + open_log( mLogFilename ); // Begin logging progress . . . - if (mRewrapFlag && mAppendIdOffsetFlag) { - log("BEGIN \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + SOURCE_NSS_DB_PATH + SPACE - + mSourcePKISecurityDatabasePath + SPACE - + SOURCE_STORAGE_TOKEN_NAME + SPACE + TIC - + mSourceStorageTokenName + TIC + SPACE - + SOURCE_STORAGE_CERT_NICKNAME + SPACE + TIC - + mSourceStorageCertNickname + TIC + SPACE - + TARGET_STORAGE_CERTIFICATE_FILE + SPACE - + mTargetStorageCertificateFilename + SPACE - + use_PKI_security_database_pwdfile + APPEND_ID_OFFSET - + SPACE + append_id_offset - + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\" . . ." - + NEWLINE, true); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - log("BEGIN \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + SOURCE_NSS_DB_PATH + SPACE - + mSourcePKISecurityDatabasePath + SPACE - + SOURCE_STORAGE_TOKEN_NAME + SPACE + TIC - + mSourceStorageTokenName + TIC + SPACE - + SOURCE_STORAGE_CERT_NICKNAME + SPACE + TIC - + mSourceStorageCertNickname + TIC + SPACE - + TARGET_STORAGE_CERTIFICATE_FILE + SPACE - + mTargetStorageCertificateFilename + SPACE - + use_PKI_security_database_pwdfile + REMOVE_ID_OFFSET - + SPACE + remove_id_offset - + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\" . . ." - + NEWLINE, true); - } else if (mRewrapFlag) { - log("BEGIN \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + SOURCE_NSS_DB_PATH + SPACE - + mSourcePKISecurityDatabasePath + SPACE - + SOURCE_STORAGE_TOKEN_NAME + SPACE + TIC - + mSourceStorageTokenName + TIC + SPACE - + SOURCE_STORAGE_CERT_NICKNAME + SPACE + TIC - + mSourceStorageCertNickname + TIC + SPACE - + TARGET_STORAGE_CERTIFICATE_FILE + SPACE - + mTargetStorageCertificateFilename - + use_PKI_security_database_pwdfile - + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\" . . ." - + NEWLINE, true); - } else if (mAppendIdOffsetFlag) { - log("BEGIN \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + APPEND_ID_OFFSET + SPACE - + append_id_offset + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\" . . ." - + NEWLINE, true); - } else if (mRemoveIdOffsetFlag) { - log("BEGIN \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + REMOVE_ID_OFFSET + SPACE - + remove_id_offset + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\" . . ." - + NEWLINE, true); + if( mRewrapFlag && mAppendIdOffsetFlag ) { + log( "BEGIN \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + SOURCE_NSS_DB_PATH + SPACE + + mSourcePKISecurityDatabasePath + SPACE + + SOURCE_STORAGE_TOKEN_NAME + SPACE + + TIC + mSourceStorageTokenName + TIC + SPACE + + SOURCE_STORAGE_CERT_NICKNAME + SPACE + + TIC + mSourceStorageCertNickname + TIC + SPACE + + TARGET_STORAGE_CERTIFICATE_FILE + SPACE + + mTargetStorageCertificateFilename + SPACE + + use_PKI_security_database_pwdfile + + APPEND_ID_OFFSET + SPACE + + append_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\" . . ." + + NEWLINE, true ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + log( "BEGIN \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + SOURCE_NSS_DB_PATH + SPACE + + mSourcePKISecurityDatabasePath + SPACE + + SOURCE_STORAGE_TOKEN_NAME + SPACE + + TIC + mSourceStorageTokenName + TIC + SPACE + + SOURCE_STORAGE_CERT_NICKNAME + SPACE + + TIC + mSourceStorageCertNickname + TIC + SPACE + + TARGET_STORAGE_CERTIFICATE_FILE + SPACE + + mTargetStorageCertificateFilename + SPACE + + use_PKI_security_database_pwdfile + + REMOVE_ID_OFFSET + SPACE + + remove_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\" . . ." + + NEWLINE, true ); + } else if( mRewrapFlag ) { + log( "BEGIN \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + SOURCE_NSS_DB_PATH + SPACE + + mSourcePKISecurityDatabasePath + SPACE + + SOURCE_STORAGE_TOKEN_NAME + SPACE + + TIC + mSourceStorageTokenName + TIC + SPACE + + SOURCE_STORAGE_CERT_NICKNAME + SPACE + + TIC + mSourceStorageCertNickname + TIC + SPACE + + TARGET_STORAGE_CERTIFICATE_FILE + SPACE + + mTargetStorageCertificateFilename + + use_PKI_security_database_pwdfile + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\" . . ." + + NEWLINE, true ); + } else if( mAppendIdOffsetFlag ) { + log( "BEGIN \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + APPEND_ID_OFFSET + SPACE + + append_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\" . . ." + + NEWLINE, true ); + } else if( mRemoveIdOffsetFlag ) { + log( "BEGIN \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + REMOVE_ID_OFFSET + SPACE + + remove_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\" . . ." + + NEWLINE, true ); } // Process the DRMTOOL config file success = process_drmtool_config_file(); - if (!success) { - log("FAILED processing drmtool config file!" + NEWLINE, true); + if( !success ) { + log( "FAILED processing drmtool config file!" + + NEWLINE, true ); } else { - log("SUCCESSFULLY processed drmtool config file!" + NEWLINE, true); + log( "SUCCESSFULLY processed drmtool config file!" + + NEWLINE, true ); // Convert the source LDIF file to a target LDIF file success = convert_source_ldif_to_target_ldif(); - if (!success) { - log("FAILED converting source LDIF file --> target LDIF file!" - + NEWLINE, true); + if( !success ) { + log( "FAILED converting source LDIF file --> target LDIF file!" + + NEWLINE, true ); } else { - log("SUCCESSFULLY converted source LDIF file --> " - + "target LDIF file!" + NEWLINE, true); + log( "SUCCESSFULLY converted source LDIF file --> " + + "target LDIF file!" + + NEWLINE, true ); } } // Finish logging progress - if (mRewrapFlag && mAppendIdOffsetFlag) { - log("FINISHED \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + SOURCE_NSS_DB_PATH + SPACE - + mSourcePKISecurityDatabasePath + SPACE - + SOURCE_STORAGE_TOKEN_NAME + SPACE + TIC - + mSourceStorageTokenName + TIC + SPACE - + SOURCE_STORAGE_CERT_NICKNAME + SPACE + TIC - + mSourceStorageCertNickname + TIC + SPACE - + TARGET_STORAGE_CERTIFICATE_FILE + SPACE - + mTargetStorageCertificateFilename + SPACE - + use_PKI_security_database_pwdfile + APPEND_ID_OFFSET - + SPACE + append_id_offset - + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\"." + NEWLINE, - true); - } else if (mRewrapFlag && mRemoveIdOffsetFlag) { - log("FINISHED \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + SOURCE_NSS_DB_PATH + SPACE - + mSourcePKISecurityDatabasePath + SPACE - + SOURCE_STORAGE_TOKEN_NAME + SPACE + TIC - + mSourceStorageTokenName + TIC + SPACE - + SOURCE_STORAGE_CERT_NICKNAME + SPACE + TIC - + mSourceStorageCertNickname + TIC + SPACE - + TARGET_STORAGE_CERTIFICATE_FILE + SPACE - + mTargetStorageCertificateFilename + SPACE - + use_PKI_security_database_pwdfile + REMOVE_ID_OFFSET - + SPACE + remove_id_offset - + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\"." + NEWLINE, - true); - } else if (mRewrapFlag) { - log("FINISHED \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + SOURCE_NSS_DB_PATH + SPACE - + mSourcePKISecurityDatabasePath + SPACE - + SOURCE_STORAGE_TOKEN_NAME + SPACE + TIC - + mSourceStorageTokenName + TIC + SPACE - + SOURCE_STORAGE_CERT_NICKNAME + SPACE + TIC - + mSourceStorageCertNickname + TIC + SPACE - + TARGET_STORAGE_CERTIFICATE_FILE + SPACE - + mTargetStorageCertificateFilename - + use_PKI_security_database_pwdfile - + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\"." + NEWLINE, - true); - } else if (mAppendIdOffsetFlag) { - log("FINISHED \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + APPEND_ID_OFFSET + SPACE - + append_id_offset + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\"." + NEWLINE, - true); - } else if (mRemoveIdOffsetFlag) { - log("FINISHED \"" + DRM_TOOL + SPACE + DRMTOOL_CFG_FILE + SPACE - + mDrmtoolCfgFilename + SPACE + SOURCE_LDIF_FILE + SPACE - + mSourceLdifFilename + SPACE + TARGET_LDIF_FILE + SPACE - + mTargetLdifFilename + SPACE + LOG_FILE + SPACE - + mLogFilename + SPACE + REMOVE_ID_OFFSET + SPACE - + remove_id_offset + process_drm_naming_context_fields - + process_requests_and_key_records_only + "\"." + NEWLINE, - true); + if( mRewrapFlag && mAppendIdOffsetFlag ) { + log( "FINISHED \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + SOURCE_NSS_DB_PATH + SPACE + + mSourcePKISecurityDatabasePath + SPACE + + SOURCE_STORAGE_TOKEN_NAME + SPACE + + TIC + mSourceStorageTokenName + TIC + SPACE + + SOURCE_STORAGE_CERT_NICKNAME + SPACE + + TIC + mSourceStorageCertNickname + TIC + SPACE + + TARGET_STORAGE_CERTIFICATE_FILE + SPACE + + mTargetStorageCertificateFilename + SPACE + + use_PKI_security_database_pwdfile + + APPEND_ID_OFFSET + SPACE + + append_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\"." + + NEWLINE, true ); + } else if( mRewrapFlag && mRemoveIdOffsetFlag ) { + log( "FINISHED \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + SOURCE_NSS_DB_PATH + SPACE + + mSourcePKISecurityDatabasePath + SPACE + + SOURCE_STORAGE_TOKEN_NAME + SPACE + + TIC + mSourceStorageTokenName + TIC + SPACE + + SOURCE_STORAGE_CERT_NICKNAME + SPACE + + TIC + mSourceStorageCertNickname + TIC + SPACE + + TARGET_STORAGE_CERTIFICATE_FILE + SPACE + + mTargetStorageCertificateFilename + SPACE + + use_PKI_security_database_pwdfile + + REMOVE_ID_OFFSET + SPACE + + remove_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\"." + + NEWLINE, true ); + } else if( mRewrapFlag ) { + log( "FINISHED \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + SOURCE_NSS_DB_PATH + SPACE + + mSourcePKISecurityDatabasePath + SPACE + + SOURCE_STORAGE_TOKEN_NAME + SPACE + + TIC + mSourceStorageTokenName + TIC + SPACE + + SOURCE_STORAGE_CERT_NICKNAME + SPACE + + TIC + mSourceStorageCertNickname + TIC + SPACE + + TARGET_STORAGE_CERTIFICATE_FILE + SPACE + + mTargetStorageCertificateFilename + + use_PKI_security_database_pwdfile + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\"." + + NEWLINE, true ); + } else if( mAppendIdOffsetFlag ) { + log( "FINISHED \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + APPEND_ID_OFFSET + SPACE + + append_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\"." + + NEWLINE, true ); + } else if( mRemoveIdOffsetFlag ) { + log( "FINISHED \"" + + DRM_TOOL + SPACE + + DRMTOOL_CFG_FILE + SPACE + + mDrmtoolCfgFilename + SPACE + + SOURCE_LDIF_FILE + SPACE + + mSourceLdifFilename + SPACE + + TARGET_LDIF_FILE + SPACE + + mTargetLdifFilename + SPACE + + LOG_FILE + SPACE + + mLogFilename + SPACE + + REMOVE_ID_OFFSET + SPACE + + remove_id_offset + + process_drm_naming_context_fields + + process_requests_and_key_records_only + + "\"." + + NEWLINE, true ); } // Shutdown logging process - close_log(mLogFilename); + close_log( mLogFilename ); } } + diff --git a/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java b/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java index 241eb5cd2..f7f90a52c 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/ExtJoiner.java @@ -17,29 +17,31 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.FileInputStream; import java.io.IOException; import netscape.security.util.DerOutputStream; import netscape.security.util.DerValue; + /** - * This program joins a sequence of extensions together so that the final output - * can be used in configuration wizard for specifing extra extensions in default + * This program joins a sequence of extensions together + * so that the final output can be used in configuration + * wizard for specifing extra extensions in default * certificates (i.e. CA certificate, SSL certificate). - * + * * Usage: - * *

  *  ExtJoiner \
  *    <ext_file0> <ext_file1> ... <ext_fileN>
- * 
+ *
  *  where,
  *    <ext_file> is a file that has the base64 
  *    encoded DER encoding of an X509 Extension
  * 
  *  ExtensionSequence ::= SEQUENCE OF Extension;
- * 
+ *
  *  0 30  142: SEQUENCE {
  *  3 30   69:   SEQUENCE {
  *  5 06    3:     OBJECT IDENTIFIER issuerAltName (2 5 29 18)
@@ -59,7 +61,7 @@ import netscape.security.util.DerValue;
  *           :     }
  *           :   }
  * 
- * + * * @version $Revision$, $Date$ */ public class ExtJoiner { @@ -67,8 +69,7 @@ public class ExtJoiner { public static void main(String args[]) { try { if (args.length == 0) { - System.out - .println("Usage: ExtJoiner ... "); + System.out.println("Usage: ExtJoiner ... "); System.exit(0); } DerValue exts[] = new DerValue[args.length]; @@ -81,14 +82,14 @@ public class ExtJoiner { DerOutputStream out = new DerOutputStream(); out.putSequence(exts); - System.out.println(com.netscape.osutil.OSUtil.BtoA(out - .toByteArray())); + System.out.println(com.netscape.osutil.OSUtil.BtoA(out.toByteArray())); } catch (IOException e) { System.out.println(e.toString()); } } - public static byte[] getFileData(String fileName) throws IOException { + public static byte[] getFileData(String fileName) + throws IOException { FileInputStream fis = new FileInputStream(fileName); byte data[] = new byte[fis.available()]; @@ -97,6 +98,6 @@ public class ExtJoiner { } finally { fis.close(); } - return com.netscape.osutil.OSUtil.AtoB(new String(data)); + return com.netscape.osutil.OSUtil.AtoB(new String(data)); } } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java b/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java index 1c35a7c07..af228b9bb 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/GenExtKeyUsage.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.util.Vector; import netscape.security.util.DerOutputStream; @@ -24,12 +25,14 @@ import netscape.security.util.DerValue; import netscape.security.util.ObjectIdentifier; import netscape.security.x509.Extension; + /** - * Generates a DER-encoded Extended Key Usage extension. The first parameter is - * the criticality of the extension, true or false. The OIDs to be included in - * the extension are passed as command-line arguments. The OIDs are described in - * RFC 2459. For example, the OID for code signing is 1.3.6.1.5.5.7.3.3. - * + * Generates a DER-encoded Extended Key Usage extension. + * The first parameter is the criticality of the extension, true or false. + * The OIDs to be included in the extension are passed as command-line + * arguments. The OIDs are described in RFC 2459. For example, + * the OID for code signing is 1.3.6.1.5.5.7.3.3. + * * @version $Revision$, $Date$ */ public class GenExtKeyUsage { @@ -37,10 +40,9 @@ public class GenExtKeyUsage { public static void main(String[] args) { try { if (args.length < 2) { - System.out - .println("Usage: GenExtKeyUsage [true|false] ..."); + System.out.println("Usage: GenExtKeyUsage [true|false] ..."); System.exit(-1); - } + } boolean critical = false; @@ -49,8 +51,7 @@ public class GenExtKeyUsage { } else if (args[0].equalsIgnoreCase("false")) { critical = false; } else { - System.out - .println("Usage: GenExtKeyUsage [true|false] ..."); + System.out.println("Usage: GenExtKeyUsage [true|false] ..."); System.exit(-1); } @@ -90,8 +91,7 @@ public class GenExtKeyUsage { // BASE64 encode the whole thing and write it to stdout - System.out.println(com.netscape.osutil.OSUtil.BtoA(extdos - .toByteArray())); + System.out.println(com.netscape.osutil.OSUtil.BtoA(extdos.toByteArray())); } catch (Exception e) { e.printStackTrace(); diff --git a/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java b/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java index 766d1ae7d..609132248 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/GenIssuerAltNameExt.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.ByteArrayOutputStream; import java.net.InetAddress; @@ -31,16 +32,17 @@ import netscape.security.x509.RFC822Name; import netscape.security.x509.URIName; import netscape.security.x509.X500Name; + /** - * This program generates an issuer alternative name extension in base-64 - * encoding. The encoding output can be used with the configuration wizard. - * + * This program generates an issuer alternative name extension + * in base-64 encoding. The encoding output can be used with + * the configuration wizard. + * * Usage: - * *
  *  GenIssuerAltNameExt \
  *    <general_type0> <general_name0> ... <general_typeN> <general_nameN>
- * 
+ *
  *  where,
  *    <general_type> can be one of the following string:
  *      DNSName 
@@ -52,7 +54,7 @@ import netscape.security.x509.X500Name;
  *      X500Name
  *    <general_name> is string
  * 
- * + * * @version $Revision$, $Date$ */ public class GenIssuerAltNameExt { @@ -66,14 +68,15 @@ public class GenIssuerAltNameExt { GeneralNames gns = new GeneralNames(); for (int i = 0; i < args.length; i += 2) { - GeneralNameInterface gni = buildGeneralNameInterface(args[i], - args[i + 1]); + GeneralNameInterface gni = + buildGeneralNameInterface( + args[i], args[i + 1]); gns.addElement(gni); } - IssuerAlternativeNameExtension sane = new IssuerAlternativeNameExtension( - gns); + IssuerAlternativeNameExtension sane = + new IssuerAlternativeNameExtension(gns); output(sane); } catch (Exception e) { @@ -82,21 +85,21 @@ public class GenIssuerAltNameExt { } public static void output(IssuerAlternativeNameExtension ext) - throws Exception { - ByteArrayOutputStream os = new ByteArrayOutputStream(); + throws Exception { + ByteArrayOutputStream os = new ByteArrayOutputStream(); ext.encode(os); - System.out.println(com.netscape.osutil.OSUtil.BtoA(os.toByteArray())); + System.out.println( + com.netscape.osutil.OSUtil.BtoA(os.toByteArray()) + ); } public static void doUsage() { System.out.println(); - System.out - .println("Usage: GenIssuerAltNameExt ... "); + System.out.println("Usage: GenIssuerAltNameExt ... "); System.out.println("where,"); - System.out - .println(" can be one of the following string:"); + System.out.println(" can be one of the following string:"); System.out.println("\tDNSName"); System.out.println("\tEDIPartyName"); System.out.println("\tIPAddressName"); @@ -107,8 +110,8 @@ public class GenIssuerAltNameExt { System.out.println(" is a string"); } - public static GeneralNameInterface buildGeneralNameInterface(String type, - String value) throws Exception { + public static GeneralNameInterface buildGeneralNameInterface( + String type, String value) throws Exception { if (type.equals("DNSName")) { return new DNSName(value); } else if (type.equals("EDIPartyName")) { @@ -126,7 +129,8 @@ public class GenIssuerAltNameExt { } else if (type.equals("X500Name")) { return new X500Name(value); } else { - System.out.println("Error: unknown general_type " + type); + System.out.println("Error: unknown general_type " + + type); doUsage(); System.exit(0); return null; diff --git a/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java b/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java index e91f2983c..52fefe579 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/GenSubjectAltNameExt.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.ByteArrayOutputStream; import java.net.InetAddress; @@ -31,16 +32,17 @@ import netscape.security.x509.SubjectAlternativeNameExtension; import netscape.security.x509.URIName; import netscape.security.x509.X500Name; + /** - * This program generates an subject alternative name extension in base-64 - * encoding. The encoding output can be used with the configuration wizard. - * + * This program generates an subject alternative name extension + * in base-64 encoding. The encoding output can be used with + * the configuration wizard. + * * Usage: - * *
  *  GenSubjectAltNameExt \
  *    <general_type0> <general_name0> ... <general_typeN> <general_nameN>
- * 
+ *
  *  where,
  *    <general_type> can be one of the following string:
  *      DNSName 
@@ -52,7 +54,7 @@ import netscape.security.x509.X500Name;
  *      X500Name
  *    <general_name> is string
  * 
- * + * * @version $Revision$, $Date$ */ public class GenSubjectAltNameExt { @@ -66,14 +68,15 @@ public class GenSubjectAltNameExt { GeneralNames gns = new GeneralNames(); for (int i = 0; i < args.length; i += 2) { - GeneralNameInterface gni = buildGeneralNameInterface(args[i], - args[i + 1]); + GeneralNameInterface gni = + buildGeneralNameInterface( + args[i], args[i + 1]); gns.addElement(gni); } - SubjectAlternativeNameExtension sane = new SubjectAlternativeNameExtension( - gns); + SubjectAlternativeNameExtension sane = + new SubjectAlternativeNameExtension(gns); output(sane); } catch (Exception e) { @@ -82,21 +85,21 @@ public class GenSubjectAltNameExt { } public static void output(SubjectAlternativeNameExtension ext) - throws Exception { - ByteArrayOutputStream os = new ByteArrayOutputStream(); + throws Exception { + ByteArrayOutputStream os = new ByteArrayOutputStream(); ext.encode(os); - System.out.println(com.netscape.osutil.OSUtil.BtoA(os.toByteArray())); + System.out.println( + com.netscape.osutil.OSUtil.BtoA(os.toByteArray()) + ); } public static void doUsage() { System.out.println(); - System.out - .println("Usage: GenSubjectAltNameExt ... "); + System.out.println("Usage: GenSubjectAltNameExt ... "); System.out.println("where,"); - System.out - .println(" can be one of the following string:"); + System.out.println(" can be one of the following string:"); System.out.println("\tDNSName"); System.out.println("\tEDIPartyName"); System.out.println("\tIPAddressName"); @@ -107,8 +110,8 @@ public class GenSubjectAltNameExt { System.out.println(" is a string"); } - public static GeneralNameInterface buildGeneralNameInterface(String type, - String value) throws Exception { + public static GeneralNameInterface buildGeneralNameInterface( + String type, String value) throws Exception { if (type.equals("DNSName")) { return new DNSName(value); } else if (type.equals("EDIPartyName")) { @@ -126,7 +129,8 @@ public class GenSubjectAltNameExt { } else if (type.equals("X500Name")) { return new X500Name(value); } else { - System.out.println("Error: unknown general_type " + type); + System.out.println("Error: unknown general_type " + + type); doUsage(); System.exit(0); return null; diff --git a/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java b/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java index d4b45d15d..0b9d3932d 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/HttpClient.java @@ -42,25 +42,32 @@ import org.mozilla.jss.ssl.SSLHandshakeCompletedListener; import org.mozilla.jss.ssl.SSLSocket; import org.mozilla.jss.util.Password; + /** * This class implements a CMC Enroll client for testing. - * + * * @version $Revision$, $Date$ */ -public class HttpClient { +public class HttpClient +{ private String _host = null; private int _port = 0; private boolean _secure = false; - public static final int ARGC = 1; - static final int cipherSuites[] = { SSLSocket.SSL3_RSA_WITH_RC4_128_MD5, + public static final int ARGC = 1; + static final int cipherSuites[] = { + SSLSocket.SSL3_RSA_WITH_RC4_128_MD5, SSLSocket.SSL3_RSA_WITH_3DES_EDE_CBC_SHA, SSLSocket.SSL3_RSA_WITH_DES_CBC_SHA, SSLSocket.SSL3_RSA_EXPORT_WITH_RC4_40_MD5, SSLSocket.SSL3_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - SSLSocket.SSL3_RSA_WITH_NULL_MD5, 0 }; + SSLSocket.SSL3_RSA_WITH_NULL_MD5, + 0 + }; - public HttpClient(String host, int port, String secure) throws Exception { + public HttpClient(String host, int port, String secure) + throws Exception + { _host = host; _port = port; if (secure.equals("true")) @@ -74,79 +81,81 @@ public class HttpClient { long length = file.length(); if (length > Integer.MAX_VALUE) { - throw new IOException("Input file " + filename - + " is too large. Must be smaller than " - + Integer.MAX_VALUE); + throw new IOException("Input file " + filename + + " is too large. Must be smaller than " + Integer.MAX_VALUE); } - byte[] bytes = new byte[(int) length]; + byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length - && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { + && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { - throw new IOException("Could not completely read file " + filename); + throw new IOException("Could not completely read file "+filename); } is.close(); return bytes; } - public void send(String ifilename, String ofilename, String dbdir, - String nickname, String password, String servlet, String clientmode) - throws Exception { - byte[] b = getBytesFromFile(ifilename); - System.out.println("Total number of bytes read = " + b.length); + public void send(String ifilename, String ofilename, String dbdir, + String nickname, String password, String servlet, String clientmode) + throws Exception + { + byte[] b = getBytesFromFile(ifilename); + + System.out.println("Total number of bytes read = "+b.length); DataOutputStream dos = null; InputStream is = null; if (_secure) { try { - CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues( - dbdir, "", "", "secmod.db"); + CryptoManager.InitializationValues vals = + new CryptoManager.InitializationValues(dbdir, "", "", "secmod.db"); CryptoManager.initialize(vals); SSLSocket socket = new SSLSocket(_host, _port); int i; - for (i = SSLSocket.SSL2_RC4_128_WITH_MD5; i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) { + for (i = SSLSocket.SSL2_RC4_128_WITH_MD5; + i <= SSLSocket.SSL2_RC2_128_CBC_EXPORT40_WITH_MD5; ++i) { try { socket.setCipherPreference(i, true); - } catch (SocketException e) { + } catch( SocketException e) { } } - // skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5 - for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5; i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) { - try { + //skip SSL_EN_IDEA_128_EDE3_CBC_WITH_MD5 + for (i = SSLSocket.SSL2_DES_64_CBC_WITH_MD5; + i <= SSLSocket.SSL2_DES_192_EDE3_CBC_WITH_MD5; ++i) { + try { socket.setCipherPreference(i, true); - } catch (SocketException e) { + } catch( SocketException e) { } } for (i = 0; cipherSuites[i] != 0; ++i) { try { socket.setCipherPreference(cipherSuites[i], true); - } catch (SocketException e) { + } catch( SocketException e) { } } - SSLHandshakeCompletedListener listener = new ClientHandshakeCB( - this); - socket.addHandshakeCompletedListener(listener); + SSLHandshakeCompletedListener listener = new ClientHandshakeCB(this); + socket.addHandshakeCompletedListener(listener); if (clientmode != null && clientmode.equals("true")) { CryptoManager cm = CryptoManager.getInstance(); CryptoToken token = cm.getInternalKeyStorageToken(); - Password pass = new Password(password.toCharArray()); + Password pass = new Password(password.toCharArray()); token.login(pass); - CryptoStore store = token.getCryptoStore(); - X509Certificate cert = cm.findCertByNickname(nickname); + CryptoStore store = token.getCryptoStore(); + X509Certificate cert = cm.findCertByNickname(nickname); if (cert == null) - System.out.println("client cert is null"); + System.out.println("client cert is null"); else - System.out.println("client cert is not null"); + System.out.println("client cert is not null"); socket.setUseClientMode(true); socket.setClientCertNickname(nickname); } @@ -155,7 +164,7 @@ public class HttpClient { dos = new DataOutputStream(socket.getOutputStream()); is = socket.getInputStream(); } catch (Exception e) { - System.out.println("Exception: " + e.toString()); + System.out.println("Exception: "+e.toString()); return; } } else { @@ -164,17 +173,17 @@ public class HttpClient { is = socket.getInputStream(); } - // send request + // send request if (servlet == null) { System.out.println("Missing servlet name."); printUsage(); } else { - String s = "POST " + servlet + " HTTP/1.0\r\n"; + String s = "POST "+servlet+" HTTP/1.0\r\n"; dos.writeBytes(s); - } - dos.writeBytes("Content-length: " + b.length + "\r\n"); - dos.writeBytes("\r\n"); - dos.write(b); + } + dos.writeBytes("Content-length: " + b.length + "\r\n"); + dos.writeBytes("\r\n"); + dos.write(b); dos.flush(); FileOutputStream fof = new FileOutputStream(ofilename); @@ -182,7 +191,8 @@ public class HttpClient { int sum = 0; boolean hack = false; try { - while (true) { + while (true) + { int r = is.read(); if (r == -1) break; @@ -207,7 +217,7 @@ public class HttpClient { fof.close(); byte[] bout = getBytesFromFile(ofilename); - System.out.println("Total number of bytes read = " + bout.length); + System.out.println("Total number of bytes read = "+ bout.length); ByteArrayOutputStream bs = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bs); @@ -215,8 +225,7 @@ public class HttpClient { System.out.println(bs.toString()); System.out.println(""); - System.out.println("The response in binary format is stored in " - + ofilename); + System.out.println("The response in binary format is stored in "+ofilename); System.out.println(""); } @@ -225,8 +234,7 @@ public class HttpClient { System.out.println("Usage: HttpClient "); System.out.println("For example, HttpClient HttpClient.cfg"); System.out.println(""); - System.out - .println("The configuration file should look like as follows:"); + System.out.println("The configuration file should look like as follows:"); System.out.println(""); System.out.println("#host: host name for the http server"); System.out.println("host=host1.a.com"); @@ -234,36 +242,29 @@ public class HttpClient { System.out.println("#port: port number"); System.out.println("port=1025"); System.out.println(""); - System.out - .println("#secure: true for secure connection, false for nonsecure connection"); + System.out.println("#secure: true for secure connection, false for nonsecure connection"); System.out.println("secure=false"); System.out.println(""); - System.out - .println("#input: full path for the enrollment request, the content must be in binary format"); + System.out.println("#input: full path for the enrollment request, the content must be in binary format"); System.out.println("input=/u/doc/cmcReqCRMFBin"); System.out.println(""); - System.out - .println("#output: full path for the response in binary format"); + System.out.println("#output: full path for the response in binary format"); System.out.println("output=/u/doc/cmcResp"); System.out.println(""); - System.out - .println("#dbdir: directory for cert8.db, key3.db and secmod.db"); + System.out.println("#dbdir: directory for cert8.db, key3.db and secmod.db"); System.out.println("#This parameter will be ignored if secure=false"); System.out.println("dbdir=/u/smith/.netscape"); System.out.println(""); - System.out - .println("#clientmode: true for client authentication, false for no client authentication"); + System.out.println("#clientmode: true for client authentication, false for no client authentication"); System.out.println("#This parameter will be ignored if secure=false"); System.out.println("clientmode=false"); System.out.println(""); System.out.println("#password: password for cert8.db"); - System.out - .println("#This parameter will be ignored if secure=false and clientauth=false"); + System.out.println("#This parameter will be ignored if secure=false and clientauth=false"); System.out.println("password="); System.out.println(""); System.out.println("#nickname: nickname for client certificate"); - System.out - .println("#This parameter will be ignored if clientmode=false"); + System.out.println("#This parameter will be ignored if clientmode=false"); System.out.println("nickname="); System.out.println(""); System.out.println("#servlet: servlet name"); @@ -272,16 +273,17 @@ public class HttpClient { System.exit(0); } - public static void main(String args[]) { - String host = null, portstr = null, secure = null, dbdir = null, nickname = null; + public static void main(String args[]) + { + String host = null, portstr = null, secure = null, dbdir = null, nickname = null ; String password = null, ofilename = null, ifilename = null; String servlet = null; String clientmode = null; - System.out.println(""); + System.out.println(""); // Check that the correct # of arguments were submitted to the program - if (args.length != (ARGC)) { + if( args.length != ( ARGC ) ) { System.out.println("Wrong number of parameters:" + args.length); printUsage(); } @@ -290,10 +292,10 @@ public class HttpClient { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( - new BufferedInputStream(new FileInputStream(configFile)))); + new BufferedInputStream( + new FileInputStream(configFile)))); } catch (FileNotFoundException e) { - System.out.println("HttpClient: can't find configuration file: " - + configFile); + System.out.println("HttpClient: can't find configuration file: "+configFile); printUsage(); System.exit(1); } catch (Exception e) { @@ -312,7 +314,7 @@ public class HttpClient { String name = tokenizer.nextToken(); String val = null; if (tokenizer.countTokens() > 0) - val = tokenizer.nextToken(); + val = tokenizer.nextToken(); if (name.equals("host")) { host = val; } else if (name.equals("port")) { @@ -358,8 +360,7 @@ public class HttpClient { } if (ifilename == null) { - System.out - .println("Missing input filename for the enrollment request."); + System.out.println("Missing input filename for the enrollment request."); printUsage(); } @@ -369,7 +370,7 @@ public class HttpClient { } int port = Integer.parseInt(portstr); - + if (secure != null && secure.equals("true")) { if (dbdir == null) { System.out.println("Missing directory name for the cert7.db."); @@ -382,17 +383,16 @@ public class HttpClient { printUsage(); } if (nickname == null) { - System.out - .println("Missing nickname for the client certificate"); + System.out.println("Missing nickname for the client certificate"); printUsage(); } } } try { - HttpClient client = new HttpClient(host, port, secure); - client.send(ifilename, ofilename, dbdir, nickname, password, - servlet, clientmode); + HttpClient client = + new HttpClient(host, port, secure); + client.send(ifilename, ofilename, dbdir, nickname, password, servlet, clientmode); } catch (Exception e) { System.out.println("Error: " + e.toString()); } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java b/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java index 2ca653175..df18a3e52 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/OCSPClient.java @@ -56,223 +56,232 @@ import com.netscape.cmsutil.ocsp.SingleResponse; import com.netscape.cmsutil.ocsp.TBSRequest; import com.netscape.cmsutil.ocsp.UnknownInfo; + /** * This class implements a OCSP client for testing. - * + * * @version $Revision$, $Date$ */ -public class OCSPClient { +public class OCSPClient +{ private String _host = null; private int _port = 0; - public OCSPClient(String host, int port, String dbdir) throws Exception { + public OCSPClient(String host, int port, String dbdir) + throws Exception + { _host = host; _port = port; CryptoManager.initialize(dbdir); } - public void send(String uri, String nickname, int serialno, String output) - throws Exception { - CryptoManager manager = CryptoManager.getInstance(); + public void send(String uri, String nickname, int serialno, String output) + throws Exception + { + CryptoManager manager = CryptoManager.getInstance(); X509Certificate caCert = manager.findCertByNickname(nickname); OCSPRequest request = getOCSPRequest(caCert, serialno); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - request.encode(os); - byte request_data[] = os.toByteArray(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + request.encode(os); + byte request_data[] = os.toByteArray(); sendOCSPRequest(uri, _host, _port, request_data, output); } - public void sendRequestData(String uri, String nickname, - byte request_data[], String output) throws Exception { + public void sendRequestData(String uri, String nickname, byte request_data[], String output) + throws Exception + { sendOCSPRequest(uri, _host, _port, request_data, output); } - public OCSPRequest getOCSPRequest(X509Certificate caCert, int serialno) - throws Exception { + public OCSPRequest getOCSPRequest(X509Certificate caCert, int serialno) + throws Exception + { MessageDigest md = MessageDigest.getInstance("SHA"); - // calculate issuer key hash + // calculate issuer key hash X509CertImpl x509Cert = new X509CertImpl(caCert.getEncoded()); - X509Key x509key = (X509Key) x509Cert.getPublicKey(); + X509Key x509key = (X509Key)x509Cert.getPublicKey(); byte issuerKeyHash[] = md.digest(x509key.getKey()); // calculate name hash - X500Name name = (X500Name) x509Cert.getSubjectDN(); + X500Name name = (X500Name)x509Cert.getSubjectDN(); byte issuerNameHash[] = md.digest(name.getEncoded()); // constructing the OCSP request - CertID certid = new CertID(new AlgorithmIdentifier( - new OBJECT_IDENTIFIER("1.3.14.3.2.26"), new NULL()), - new OCTET_STRING(issuerNameHash), new OCTET_STRING( - issuerKeyHash), new INTEGER(serialno)); + CertID certid = new CertID( + new AlgorithmIdentifier( + new OBJECT_IDENTIFIER("1.3.14.3.2.26"), new NULL()), + new OCTET_STRING(issuerNameHash), + new OCTET_STRING(issuerKeyHash), + new INTEGER(serialno)); Request request = new Request(certid, null); SEQUENCE requestList = new SEQUENCE(); requestList.addElement(request); - TBSRequest tbsRequest = new TBSRequest(null, null, requestList, null); + TBSRequest tbsRequest = new TBSRequest(null,null,requestList,null); return new OCSPRequest(tbsRequest, null); } - public void sendOCSPRequest(String uri, String host, int port, - byte request_data[], String output) throws Exception { + public void sendOCSPRequest(String uri, String host, int port, + byte request_data[], String output) throws Exception + { Socket socket = new Socket(host, port); - // send request + // send request System.out.println("URI: " + uri); - DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); - dos.writeBytes("POST " + uri + " HTTP/1.0\r\n"); - dos.writeBytes("Content-length: " + request_data.length + "\r\n"); - dos.writeBytes("\r\n"); - dos.write(request_data); + DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); + dos.writeBytes("POST " + uri + " HTTP/1.0\r\n"); + dos.writeBytes("Content-length: " + request_data.length + "\r\n"); + dos.writeBytes("\r\n"); + dos.write(request_data); dos.flush(); System.out.println("Data Length: " + request_data.length); - System.out.println("Data: " - + com.netscape.osutil.OSUtil.BtoA(request_data)); + System.out.println("Data: " + com.netscape.osutil.OSUtil.BtoA(request_data)); - InputStream iiss = socket.getInputStream(); + InputStream iiss = socket.getInputStream(); FileOutputStream fof = new FileOutputStream(output); - boolean startSaving = false; - int sum = 0; - boolean hack = false; - try { - while (true) { - int r = iiss.read(); - if (r == -1) - break; - if (r == 10) { - sum++; - } - if (sum == 6) { - startSaving = true; - continue; - } - if (startSaving) { - if (hack) { - fof.write(r); - } - if (hack == false) { - hack = true; - } - } - } // while - } catch (IOException e) { - } + boolean startSaving = false; + int sum = 0; + boolean hack = false; + try { + while (true) + { + int r = iiss.read(); + if (r == -1) + break; + if (r == 10) { + sum++; + } + if (sum == 6) { + startSaving = true; + continue; + } + if (startSaving) { + if (hack) { + fof.write(r); + } + if (hack == false) { + hack = true; + } + } + } // while + } catch (IOException e) { + } fof.close(); - // parse OCSPResponse - BufferedInputStream fis = new BufferedInputStream(new FileInputStream( - output)); - OCSPResponse resp = (OCSPResponse) OCSPResponse.getTemplate().decode( - fis); - OCSPResponseStatus status = resp.getResponseStatus(); + // parse OCSPResponse + BufferedInputStream fis = + new BufferedInputStream( + new FileInputStream(output)); + OCSPResponse resp = (OCSPResponse) + OCSPResponse.getTemplate().decode(fis); + OCSPResponseStatus status = resp.getResponseStatus(); ResponseBytes bytes = resp.getResponseBytes(); - BasicOCSPResponse basic = (BasicOCSPResponse) BasicOCSPResponse - .getTemplate().decode( - new ByteArrayInputStream(bytes.getResponse() - .toByteArray())); + BasicOCSPResponse basic = (BasicOCSPResponse) + BasicOCSPResponse.getTemplate().decode( + new ByteArrayInputStream(bytes.getResponse().toByteArray())); ResponseData rd = basic.getResponseData(); for (int i = 0; i < rd.getResponseCount(); i++) { - SingleResponse rd1 = rd.getResponseAt(i); - System.out.println("CertID.serialNumber=" - + rd1.getCertID().getSerialNumber()); - CertStatus status1 = rd1.getCertStatus(); - if (status1 instanceof GoodInfo) { - System.out.println("CertStatus=Good"); - } - if (status1 instanceof UnknownInfo) { - System.out.println("CertStatus=Unknown"); - } - if (status1 instanceof RevokedInfo) { - System.out.println("CertStatus=Revoked"); - } + SingleResponse rd1 = rd.getResponseAt(i); + System.out.println("CertID.serialNumber=" + + rd1.getCertID().getSerialNumber()); + CertStatus status1 = rd1.getCertStatus(); + if (status1 instanceof GoodInfo) { + System.out.println("CertStatus=Good"); + } + if (status1 instanceof UnknownInfo) { + System.out.println("CertStatus=Unknown"); + } + if (status1 instanceof RevokedInfo) { + System.out.println("CertStatus=Revoked"); + } } } - public static void printUsage() { - System.out - .println("Usage: OCSPClient " - + " "); - System.out.println(" = OCSP server hostname"); - System.out.println(" = OCSP server port number"); - System.out.println(" = Certificate Database Directory"); - System.out.println(" = Nickname of CA Certificate"); - System.out - .println(" = Serial Number Being Checked, Or Name of file that contains the request"); - System.out - .println(" = Filename of Response in DER encoding"); - System.out.println(" = Submit Request Multiple Times"); - System.out - .println(" [] = OCSP Service URI (i.e. /ocsp/ee/ocsp)"); + public static void printUsage() + { + System.out.println("Usage: OCSPClient " + + " "); + System.out.println(" = OCSP server hostname"); + System.out.println(" = OCSP server port number"); + System.out.println(" = Certificate Database Directory"); + System.out.println(" = Nickname of CA Certificate"); + System.out.println(" = Serial Number Being Checked, Or Name of file that contains the request"); + System.out.println(" = Filename of Response in DER encoding"); + System.out.println(" = Submit Request Multiple Times"); + System.out.println(" [] = OCSP Service URI (i.e. /ocsp/ee/ocsp)"); } - public static void main(String args[]) { - if (args.length != 7 && args.length != 8) { + public static void main(String args[]) + { + if (args.length != 7 && args.length !=8 ) + { System.out.println("ERROR: Invalid number of arguments - got " - + args.length + " expected 7!"); + + args.length + " expected 7!"); for (int i = 0; i < args.length; i++) { - System.out.println("arg[" + i + "]=" + args[i]); + System.out.println("arg[" + i + "]=" + args[i]); } printUsage(); - System.exit(0); + System.exit(0); } String host = args[0]; int port = -1; try { - port = Integer.parseInt(args[1]); + port = Integer.parseInt(args[1]); } catch (Exception e) { - System.out.println("Error: Invalid Port Number"); - printUsage(); - System.exit(0); + System.out.println("Error: Invalid Port Number"); + printUsage(); + System.exit(0); } String dbdir = args[2]; String nickname = args[3]; int serialno = -1; byte data[] = null; try { - serialno = Integer.parseInt(args[4]); + serialno = Integer.parseInt(args[4]); } catch (Exception e) { - try { - System.out - .println("Warning: Serial Number not found. It may be a filename."); - /* it could be a file name */ - FileInputStream fis = new FileInputStream(args[4]); - System.out.println("File Size: " + fis.available()); - data = new byte[fis.available()]; - fis.read(data); - } catch (Exception e1) { - System.out.println("Error: Invalid Serial Number or File Name"); - printUsage(); - System.exit(0); - } + try { + System.out.println("Warning: Serial Number not found. It may be a filename."); + /* it could be a file name */ + FileInputStream fis = new FileInputStream(args[4]); + System.out.println("File Size: " + fis.available()); + data = new byte[fis.available()]; + fis.read(data); + } catch (Exception e1) { + System.out.println("Error: Invalid Serial Number or File Name"); + printUsage(); + System.exit(0); + } } String output = args[5]; int times = 1; try { - times = Integer.parseInt(args[6]); + times = Integer.parseInt(args[6]); } catch (Exception e) { - System.out.println("Error: Invalid Times"); - printUsage(); - System.exit(0); + System.out.println("Error: Invalid Times"); + printUsage(); + System.exit(0); } String uri = "/ocsp/ee/ocsp"; if (args.length > 7) { - uri = args[7]; + uri = args[7]; } try { - OCSPClient client = new OCSPClient(host, port, dbdir); - for (int i = 0; i < times; i++) { - if (data != null) { - client.sendRequestData(uri, nickname, data, output); - } else { - client.send(uri, nickname, serialno, output); - } + OCSPClient client = + new OCSPClient(host, port, dbdir); + for (int i = 0; i < times; i ++) { + if (data != null) { + client.sendRequestData(uri, nickname, data, output); + } else { + client.send(uri, nickname, serialno, output); + } } System.out.println("Success: Output " + output); } catch (Exception e) { System.out.println("Error: " + e.toString()); printUsage(); - System.exit(0); + System.exit(0); } } } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java b/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java index 6641e3be4..5f0999119 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/PKCS10Client.java @@ -46,31 +46,32 @@ import org.mozilla.jss.util.Password; import com.netscape.cmsutil.util.HMACDigest; + /** * Generates a 1024-bit RSA key pair in the security database, constructs a - * PKCS#10 certificate request with the public key, and outputs the request to a - * file. + * PKCS#10 certificate request with the public key, and outputs the request + * to a file. *

- * PKCS #10 is a certification request syntax standard defined by RSA. A CA may - * support multiple types of certificate requests. The Certificate System CA - * supports KEYGEN, PKCS#10, CRMF, and CMC. + * PKCS #10 is a certification request syntax standard defined by RSA. A CA + * may support multiple types of certificate requests. The Certificate System + * CA supports KEYGEN, PKCS#10, CRMF, and CMC. *

* To get a certificate from the CA, the certificate request needs to be * submitted to and approved by a CA agent. Once approved, a certificate is - * created for the request, and certificate attributes, such as extensions, are - * populated according to certificate profiles. + * created for the request, and certificate attributes, such as extensions, + * are populated according to certificate profiles. *

- * * @version $Revision$, $Date$ */ -public class PKCS10Client { - +public class PKCS10Client +{ + private static void printUsage() { - System.out - .println("Usage: PKCS10Client -p -d -o -s \n"); + System.out.println("Usage: PKCS10Client -p -d -o -s \n"); } - public static void main(String args[]) { + public static void main(String args[]) + { String dbdir = null, ofilename = null, password = null, subjectName = null; if (args.length != 8) { @@ -78,32 +79,33 @@ public class PKCS10Client { System.exit(1); } - for (int i = 0; i < args.length; i++) { + for (int i=0; i - * * @version $Revision$, $Date$ - * + * */ public class PKCS12Export { @@ -66,16 +67,14 @@ public class PKCS12Export { private static void debug(String s) { if (debugMode) - System.out.println("PKCS12Export debug: " + s); + System.out.println("PKCS12Export debug: " + s); } private static void printUsage() { - System.out - .println("Usage: PKCS12Export -d -p -w -o "); + System.out.println("Usage: PKCS12Export -d -p -w -o "); System.out.println(""); System.out.println("If you want to turn on debug, do the following:"); - System.out - .println("Usage: PKCS12Export -debug -d -p -w -o "); + System.out.println("Usage: PKCS12Export -debug -d -p -w -o "); } private static byte[] getEncodedKey(org.mozilla.jss.crypto.PrivateKey pkey) { @@ -84,9 +83,8 @@ public class PKCS12Export { CryptoToken token = cm.getInternalKeyStorageToken(); KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3); SymmetricKey sk = kg.generate(); - KeyWrapper wrapper = token - .getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD); - byte iv[] = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; + KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD); + byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1}; IVParameterSpec param = new IVParameterSpec(iv); wrapper.initWrap(sk, param); byte[] enckey = wrapper.wrap(pkey); @@ -95,39 +93,38 @@ public class PKCS12Export { byte[] recovered = c.doFinal(enckey); return recovered; } catch (Exception e) { - debug("PKCS12Export getEncodedKey: Exception=" + e.toString()); + debug("PKCS12Export getEncodedKey: Exception="+e.toString()); System.exit(1); } return null; } - private static void addKeyBag(org.mozilla.jss.crypto.PrivateKey pkey, - X509Certificate x509cert, Password pass, byte[] localKeyId, - SEQUENCE safeContents) { + private static void addKeyBag(org.mozilla.jss.crypto.PrivateKey pkey, X509Certificate x509cert, + Password pass, byte[] localKeyId, SEQUENCE safeContents) { try { PasswordConverter passConverter = new PasswordConverter(); - byte salt[] = { 0x01, 0x01, 0x01, 0x01 }; + byte salt[] = {0x01, 0x01, 0x01, 0x01}; byte[] priData = getEncodedKey(pkey); - PrivateKeyInfo pki = (PrivateKeyInfo) ASN1Util.decode( - PrivateKeyInfo.getTemplate(), priData); + PrivateKeyInfo pki = (PrivateKeyInfo) + ASN1Util.decode(PrivateKeyInfo.getTemplate(), priData); ASN1Value key = EncryptedPrivateKeyInfo.createPBE( - PBEAlgorithm.PBE_SHA1_DES3_CBC, pass, salt, 1, - passConverter, pki); - SET keyAttrs = createBagAttrs(x509cert.getSubjectDN().toString(), - localKeyId); - SafeBag keyBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG, key, - keyAttrs); + PBEAlgorithm.PBE_SHA1_DES3_CBC, + pass, salt, 1, passConverter, pki); + SET keyAttrs = createBagAttrs( + x509cert.getSubjectDN().toString(), localKeyId); + SafeBag keyBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG, + key, keyAttrs); safeContents.addElement(keyBag); } catch (Exception e) { - debug("PKCS12Export addKeyBag: Exception=" + e.toString()); + debug("PKCS12Export addKeyBag: Exception="+e.toString()); System.exit(1); } } private static byte[] addCertBag(X509Certificate x509cert, String nickname, - SEQUENCE safeContents) throws IOException { + SEQUENCE safeContents) throws IOException { byte[] localKeyId = null; try { ASN1Value cert = new OCTET_STRING(x509cert.getEncoded()); @@ -135,11 +132,11 @@ public class PKCS12Export { SET certAttrs = null; if (nickname != null) certAttrs = createBagAttrs(nickname, localKeyId); - SafeBag certBag = new SafeBag(SafeBag.CERT_BAG, new CertBag( - CertBag.X509_CERT_TYPE, cert), certAttrs); + SafeBag certBag = new SafeBag(SafeBag.CERT_BAG, + new CertBag(CertBag.X509_CERT_TYPE, cert), certAttrs); safeContents.addElement(certBag); } catch (Exception e) { - debug("PKCS12Export addCertBag: " + e.toString()); + debug("PKCS12Export addCertBag: "+e.toString()); System.exit(1); } @@ -156,7 +153,7 @@ public class PKCS12Export { md.update(certDer); return md.digest(); } catch (Exception e) { - debug("PKCS12Export createLocalKeyId: Exception: " + e.toString()); + debug("PKCS12Export createLocalKeyId: Exception: "+e.toString()); System.exit(1); } @@ -164,7 +161,7 @@ public class PKCS12Export { } private static SET createBagAttrs(String nickName, byte localKeyId[]) - throws IOException { + throws IOException { try { SET attrs = new SET(); SEQUENCE nickNameAttr = new SEQUENCE(); @@ -185,7 +182,7 @@ public class PKCS12Export { attrs.addElement(localKeyAttr); return attrs; } catch (Exception e) { - debug("PKCS12Export createBagAttrs: Exception=" + e.toString()); + debug("PKCS12Export createBagAttrs: Exception="+e.toString()); System.exit(1); } @@ -203,24 +200,24 @@ public class PKCS12Export { String snickname = null; String pk12pwdfile = null; String pk12output = null; - for (int i = 0; i < args.length; i++) { + for (int i=0; i/config directory, unless the file's full path is specified in the -c option..\nUsage: PasswordCache <-d cert/key db directory> <-h tokenName> <-P cert/key db prefix> <-c pwcache.db_file_full_path> <-k file containing Base64EncodedKeyID> ..."); - System.out.println(" commands:"); - System.out.println(" 'add '"); - System.out.println(" 'change '"); - System.out.println(" 'delete '"); - System.out.println(" 'rekey'"); - System.out.println(" 'list'"); - System.out - .println("\nExample:\n\tPasswordCache thePassword1 -d /usr/netscape/servers/cms/alias -P cert-instance1-machine1- -c pwcache.db -k keyidFile list"); - System.exit(1); + System.out.println("This tool has to be run from the same directory where pwcache.db file resides, normally /config directory, unless the file's full path is specified in the -c option..\nUsage: PasswordCache <-d cert/key db directory> <-h tokenName> <-P cert/key db prefix> <-c pwcache.db_file_full_path> <-k file containing Base64EncodedKeyID> ..."); + System.out.println(" commands:"); + System.out.println(" 'add '"); + System.out.println(" 'change '"); + System.out.println(" 'delete '"); + System.out.println(" 'rekey'"); + System.out.println(" 'list'"); + System.out.println("\nExample:\n\tPasswordCache thePassword1 -d /usr/netscape/servers/cms/alias -P cert-instance1-machine1- -c pwcache.db -k keyidFile list"); + System.exit(1); } private static boolean debugMode = false; @@ -80,24 +79,26 @@ public class PasswordCache { public PasswordCache() { } - private static void debug(String s) { + private static void debug (String s) { if (debugMode == true) - System.out.println("PasswordCache debug: " + s); + System.out.println("PasswordCache debug: "+s); } /** * clean up an argv by removing the trailing, empty arguments - * - * This is necessary to support the script wrapper which calls the tool with - * arguments in quotes such as: "$1" "$2" if $2 is not specified, the empty - * arg "" gets passed, which causes an error in the arg-count checking code. + * + * This is necessary to support the script wrapper which calls the + * tool with arguments in quotes such as: + * "$1" "$2" + * if $2 is not specified, the empty arg "" gets passed, which causes + * an error in the arg-count checking code. */ private static String[] cleanArgs(String[] s) { int length; int i; length = s.length; - debug("before cleanArgs argv length =" + length); + debug("before cleanArgs argv length ="+length); for (i = length - 1; i >= 0; i--) { if (s[i].equals("")) { @@ -110,24 +111,27 @@ public class PasswordCache { String[] new_av = new String[length]; for (i = 0; i < length; i++) { new_av[i] = s[i]; - debug("arg " + i + " is " + new_av[i]); + debug("arg "+i+" is "+new_av[i]); } - debug("after cleanArgs argv length =" + length); + debug("after cleanArgs argv length ="+length); return new_av; } public static byte[] base64Decode(String s) throws IOException { - byte[] d = com.netscape.osutil.OSUtil.AtoB(s); - return d; + byte[] d = com.netscape.osutil.OSUtil.AtoB(s); + return d; } public static String base64Encode(byte[] bytes) throws IOException { // All this streaming is lame, but Base64OutputStream needs a // PrintStream ByteArrayOutputStream output = new ByteArrayOutputStream(); - Base64OutputStream b64 = new Base64OutputStream(new PrintStream( - new FilterOutputStream(output))); + Base64OutputStream b64 = new Base64OutputStream(new + PrintStream(new + FilterOutputStream(output) + ) + ); b64.write(bytes); b64.flush(); @@ -137,7 +141,7 @@ public class PasswordCache { return output.toString("8859_1"); } - public static void main(String[] av) { + public static void main(String[]av) { // default path is "." String mPath = "."; String mTokenName = null; @@ -169,34 +173,28 @@ public class PasswordCache { String aPasswd = ""; int i = 0; - for (i = 1; i < argv.length; ++i) { - if (argv[i].equals("-d")) { - if (++i >= argv.length) - usage(); + for ( i = 1; i < argv.length; ++i) { + if( argv[i].equals("-d") ) { + if( ++i >= argv.length ) usage(); mPath = argv[i]; - } else if (argv[i].equals("-h")) { - if (++i >= argv.length) - usage(); + } else if( argv[i].equals("-h") ) { + if( ++i >= argv.length ) usage(); mTokenName = argv[i]; - } else if (argv[i].equals("-P")) { - if (++i >= argv.length) - usage(); + } else if( argv[i].equals("-P") ) { + if( ++i >= argv.length ) usage(); mPrefix = argv[i]; - } else if (argv[i].equals("-c")) { - if (++i >= argv.length) - usage(); + } else if( argv[i].equals("-c") ) { + if( ++i >= argv.length ) usage(); mCacheFile = argv[i]; - } else if (argv[i].equals("-k")) { - if (++i >= argv.length) - usage(); + } else if (argv[i].equals("-k") ) { + if( ++i >= argv.length ) usage(); String keyFile = argv[i]; try { - BufferedReader r = new BufferedReader(new FileReader( - keyFile)); - String listLine; - mKeyIdString = r.readLine(); + BufferedReader r = new BufferedReader(new FileReader(keyFile)); + String listLine; + mKeyIdString = r.readLine(); } catch (Exception e) { - System.out.println("Error: " + e.toString()); + System.out.println("Error: "+e.toString()); System.exit(1); } @@ -205,19 +203,19 @@ public class PasswordCache { mKeyId = base64Decode(mKeyIdString); debug("base64Decode of key id string successful"); } catch (IOException e) { - System.out - .println("base64Decode of key id string failed"); + System.out.println("base64Decode of key id string failed"); System.exit(1); } } } else { command = argv[i++]; - debug("command = " + command); + debug("command = "+command); - if ((command.equals("add")) || (command.equals("change"))) { + if ((command.equals("add")) || + (command.equals("change"))) { aTag = argv[i++]; aPasswd = argv[i]; - debug("command is " + command + " " + aTag + ":" + aPasswd); + debug("command is "+command+" "+aTag+":"+aPasswd); } else if (command.equals("delete")) { aTag = argv[i]; } else if (command.equals("list")) { @@ -233,8 +231,9 @@ public class PasswordCache { System.out.println("cert/key db path = " + mPath); System.out.println("password cache file = " + mCacheFile); - CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues( - mPath, mPrefix, mPrefix, "secmod.db"); + CryptoManager.InitializationValues vals = + new CryptoManager.InitializationValues(mPath, mPrefix, + mPrefix, "secmod.db"); CryptoManager.initialize(vals); @@ -245,7 +244,7 @@ public class PasswordCache { System.out.println("token name = internal"); } else { token = cm.getTokenByName(mTokenName); - System.out.println("token name = " + mTokenName); + System.out.println("token name = "+ mTokenName); } token.login(pass); @@ -260,37 +259,34 @@ public class PasswordCache { PWsdrCache cache = null; try { // compose instance name - File passwordCacheDB = new File(mCacheFile); + File passwordCacheDB = new File( mCacheFile ); pwdPath = passwordCacheDB.getAbsolutePath(); - int beginIndex = pwdPath.lastIndexOf("cert-"); - instancePath = pwdPath.substring(beginIndex); + int beginIndex = pwdPath.lastIndexOf( "cert-" ); + instancePath = pwdPath.substring( beginIndex ); int endIndex = 0; - endIndex = instancePath.lastIndexOf("config"); - instanceName = instancePath.substring(0, (endIndex - 1)); - - cache = new PWsdrCache(mCacheFile, mTokenName, null, true); - cache.deleteUniqueNamedKey(PROP_PWC_NICKNAME + " " - + instanceName); - byte[] newKeyId = cache - .generateSDRKeyWithNickName(PROP_PWC_NICKNAME + " " - + instanceName); + endIndex = instancePath.lastIndexOf( "config" ); + instanceName = instancePath.substring( 0, ( endIndex - 1 ) ); + + cache = new PWsdrCache(mCacheFile, mTokenName, null, true); + cache.deleteUniqueNamedKey( PROP_PWC_NICKNAME + + " " + + instanceName ); + byte[] newKeyId = cache.generateSDRKeyWithNickName( + PROP_PWC_NICKNAME + + " " + + instanceName ); if (newKeyId != null) { String newKeyIDString = base64Encode(newKeyId); - System.out - .println("key generated successfully with key id = " - + newKeyIDString); - System.out - .println("Save the VALUE portion of this key id in a local file,"); - System.out - .println("and under variable \"pwcKeyid\" in CS.cfg !!"); + System.out.println("key generated successfully with key id = "+ + newKeyIDString); + System.out.println("Save the VALUE portion of this key id in a local file,"); + System.out.println("and under variable \"pwcKeyid\" in CS.cfg !!"); System.out.println("If you have not already done so,"); - System.out - .println("remove the old pwcache.db and use this local file to add passwords."); - // job is done + System.out.println("remove the old pwcache.db and use this local file to add passwords."); + // job is done System.exit(0); } else { - System.out - .println("key expected to be generated but wasn't"); + System.out.println("key expected to be generated but wasn't"); System.exit(1); } } catch (Exception e) { @@ -301,10 +297,10 @@ public class PasswordCache { PWsdrCache cache = null; try { - cache = new PWsdrCache(mCacheFile, mTokenName, mKeyId, true); + cache = new PWsdrCache(mCacheFile, mTokenName, mKeyId, true); } catch (Exception e) { System.out.println(e.toString()); - System.exit(1); + System.exit(1); } if ((command.equals("add")) || (command.equals("change"))) { @@ -314,12 +310,12 @@ public class PasswordCache { System.exit(1); } - try { - System.out.println("adding " + aTag + ":" + aPasswd); - cache.addEntry(aTag, aPasswd); - } catch (Exception e) { - System.out.println("--failed--" + e.toString()); - } + try { + System.out.println("adding "+aTag+":"+aPasswd); + cache.addEntry(aTag, aPasswd); + } catch (Exception e) { + System.out.println("--failed--"+ e.toString()); + } } else if (command.equals("list")) { cache.pprint(); } else if (command.equals("delete")) { @@ -329,11 +325,11 @@ public class PasswordCache { System.exit(1); } - try { - cache.deleteEntry(aTag); - } catch (Exception e) { - System.out.println("User not found"); - } + try { + cache.deleteEntry(aTag); + } catch (Exception e) { + System.out.println("User not found"); + } } else { System.out.println("Illegal command: " + command); System.exit(1); @@ -341,25 +337,29 @@ public class PasswordCache { } private static boolean badPassword(String pwd) { - // XXX - implement only password checking - return false; - /* - * PasswordChecker pwdChecker = new PasswordChecker(); - * - * if (!pwdChecker.isGoodPassword(pwd)) { String reason = - * pwdChecker.getReason(pwd); - * - * System.out.println("New password does not pass password " + - * "quality test: " + reason); return true; } else { return false; } - */ + // XXX - implement only password checking + return false; +/* + PasswordChecker pwdChecker = new PasswordChecker(); + + if (!pwdChecker.isGoodPassword(pwd)) { + String reason = pwdChecker.getReason(pwd); + + System.out.println("New password does not pass password " + + "quality test: " + reason); + return true; + } else { + return false; + } +*/ } } -/* + +/* * A class for managing passwords in the SDR password cache - * + * * @author Christina Fu - * * @version $Revision$, $Date$ */ class PWsdrCache { @@ -376,7 +376,7 @@ class PWsdrCache { // for PasswordCache tool (isTool == true) public PWsdrCache(String pwCache, String pwcTokenname, byte[] keyId, - boolean isTool) throws Exception { + boolean isTool) throws Exception { mPWcachedb = pwCache; mIsTool = isTool; mTokenName = pwcTokenname; @@ -389,9 +389,9 @@ class PWsdrCache { cm = CryptoManager.getInstance(); if (mTokenName != null) { mToken = cm.getTokenByName(mTokenName); - debug("PWsdrCache: mToken = " + mTokenName); + debug("PWsdrCache: mToken = "+mTokenName); } else { - mToken = cm.getInternalKeyStorageToken(); + mToken = cm.getInternalKeyStorageToken(); debug("PWsdrCache: mToken = internal"); } } @@ -404,38 +404,42 @@ class PWsdrCache { return mTokenName; } - public void deleteUniqueNamedKey(String nickName) throws Exception { - KeyManager km = new KeyManager(mToken); - km.deleteUniqueNamedKey(nickName); + public void deleteUniqueNamedKey( String nickName ) + throws Exception + { + KeyManager km = new KeyManager( mToken ); + km.deleteUniqueNamedKey( nickName ); } public byte[] generateSDRKey() throws Exception { - return generateSDRKeyWithNickName(PROP_PWC_NICKNAME); + return generateSDRKeyWithNickName(PROP_PWC_NICKNAME); } - public byte[] generateSDRKeyWithNickName(String nickName) throws Exception { + public byte[] generateSDRKeyWithNickName( String nickName ) + throws Exception + { try { if (mIsTool == true) { // generate SDR key - KeyManager km = new KeyManager(mToken); + KeyManager km = new KeyManager(mToken); try { - // Bugscape Bug #54838: Due to the CMS cloning feature, - // we must check for the presence of - // a uniquely named symmetric key - // prior to making an attempt to - // generate it! + // Bugscape Bug #54838: Due to the CMS cloning feature, + // we must check for the presence of + // a uniquely named symmetric key + // prior to making an attempt to + // generate it! // - if (!(km.uniqueNamedKeyExists(nickName))) { - mKeyID = km.generateUniqueNamedKey(nickName); + if( !( km.uniqueNamedKeyExists( nickName ) ) ) { + mKeyID = km.generateUniqueNamedKey( nickName ); debug("PWsdrCache: SDR key generated"); } } catch (TokenException e) { - log(0, "generateSDRKey() failed on " + e.toString()); + log (0, "generateSDRKey() failed on "+e.toString()); throw e; } } } catch (Exception e) { - log(0, e.toString()); + log (0, e.toString()); throw e; } return mKeyID; @@ -455,9 +459,8 @@ class PWsdrCache { /* * add passwd in pwcache. */ - public void addEntry(String tag, String pwd, Hashtable tagPwds) - throws IOException { - System.out.println("PWsdrCache: in addEntry"); + public void addEntry(String tag, String pwd, Hashtable tagPwds) throws IOException { + System.out.println("PWsdrCache: in addEntry"); String stringToAdd = null; String bufs = null; @@ -470,7 +473,7 @@ class PWsdrCache { tag = (String) enum1.nextElement(); pwd = (String) tagPwds.get(tag); debug("password tag: " + tag + " stored in " + mPWcachedb); - + if (stringToAdd == null) { stringToAdd = tag + ":" + pwd + "\n"; } else { @@ -483,7 +486,7 @@ class PWsdrCache { System.out.println("PWsdrCache: after readPWcache()"); if (dcrypts != null) { // converts to Hashtable, replace if tag exists, add - // if tag doesn't exist + // if tag doesn't exist Hashtable ht = string2Hashtable(dcrypts); if (ht.containsKey(tag) == false) { @@ -498,7 +501,7 @@ class PWsdrCache { debug("adding new tag: " + tag); bufs = stringToAdd; } - + // write update to cache writePWcache(bufs); } @@ -513,7 +516,7 @@ class PWsdrCache { if (dcrypts != null) { // converts to Hashtable, replace if tag exists, add - // if tag doesn't exist + // if tag doesn't exist Hashtable ht = string2Hashtable(dcrypts); if (ht.containsKey(tag) == false) { @@ -528,7 +531,7 @@ class PWsdrCache { debug("password cache contains no tags"); return; } - + // write update to cache writePWcache(bufs); } @@ -563,12 +566,10 @@ class PWsdrCache { } inputs.close(); } catch (FileNotFoundException e) { - System.out.println("Failed for file " + mPWcachedb + " " - + e.toString()); + System.out.println("Failed for file " + mPWcachedb + " " + e.toString()); throw new IOException(e.toString() + ": " + mPWcachedb); } catch (IOException e) { - System.out.println("Failed for file " + mPWcachedb + " " - + e.toString()); + System.out.println("Failed for file " + mPWcachedb + " " + e.toString()); throw new IOException(e.toString() + ": " + mPWcachedb); } @@ -579,18 +580,15 @@ class PWsdrCache { dcrypts = new String(dcryptb, "UTF-8"); } catch (TokenException e) { - System.out.println("password cache decrypto failed " - + e.toString()); + System.out.println("password cache decrypto failed " + e.toString()); e.printStackTrace(); throw new IOException("password cache decrypt failed"); } catch (UnsupportedEncodingException e) { - System.out.println("password cache decrypto failed " - + e.toString()); + System.out.println("password cache decrypto failed " + e.toString()); e.printStackTrace(); throw new IOException("password cache decrypt failed"); } catch (Exception e) { - System.out.println("password cache decrypto failed " - + e.toString()); + System.out.println("password cache decrypto failed " + e.toString()); e.printStackTrace(); throw new IOException("password cache decrypt failed"); } @@ -604,9 +602,10 @@ class PWsdrCache { */ public void writePWcache(String bufs) throws IOException { + try { Encryptor sdr = new Encryptor(mToken, mKeyID, - Encryptor.DEFAULT_ENCRYPTION_ALG); + Encryptor.DEFAULT_ENCRYPTION_ALG); byte[] writebuf = null; @@ -614,8 +613,7 @@ class PWsdrCache { // now encrypt it again writebuf = sdr.encrypt(bufs.getBytes("UTF-8")); } catch (Exception e) { - System.out.println("password cache encrypt failed " - + e.toString()); + System.out.println("password cache encrypt failed " + e.toString()); e.printStackTrace(); throw new IOException("password cache encrypt failed"); } @@ -626,55 +624,53 @@ class PWsdrCache { // it wasn't removed? tmpPWcache.delete(); } - FileOutputStream outstream = new FileOutputStream(mPWcachedb - + ".tmp"); + FileOutputStream outstream = new FileOutputStream(mPWcachedb + ".tmp"); outstream.write(writebuf); outstream.close(); // Make certain that this temporary file has // the correct permissions. - if (!isNT()) { - exec("chmod 00660 " + tmpPWcache.getAbsolutePath()); + if( !isNT() ) { + exec( "chmod 00660 " + tmpPWcache.getAbsolutePath() ); } File origFile = new File(mPWcachedb); try { // Always remove any pre-existing target file - if (origFile.exists()) { + if( origFile.exists() ) { origFile.delete(); } if (isNT()) { // NT is very picky on the path - exec("copy " - + tmpPWcache.getAbsolutePath().replace('/', '\\') - + " " - + origFile.getAbsolutePath().replace('/', '\\')); + exec("copy " + + tmpPWcache.getAbsolutePath().replace('/', '\\') + " " + + origFile.getAbsolutePath().replace('/', '\\')); } else { // Create a copy of the temporary file which // preserves the temporary file's permissions. - exec("cp -p " + tmpPWcache.getAbsolutePath() + " " - + origFile.getAbsolutePath()); + exec("cp -p " + tmpPWcache.getAbsolutePath() + " " + + origFile.getAbsolutePath()); } // Remove the temporary file if and only if // the "rename" was successful. - if (origFile.exists()) { + if( origFile.exists() ) { tmpPWcache.delete(); // Make certain that the final file has // the correct permissions. - if (!isNT()) { - exec("chmod 00660 " + origFile.getAbsolutePath()); + if( !isNT() ) { + exec( "chmod 00660 " + origFile.getAbsolutePath() ); } // report success - debug("Renaming operation completed for " + mPWcachedb); + debug( "Renaming operation completed for " + mPWcachedb ); } else { // report failure and exit - debug("Renaming operation failed for " + mPWcachedb); + debug( "Renaming operation failed for " + mPWcachedb ); System.exit(1); } } catch (IOException exx) { @@ -685,8 +681,7 @@ class PWsdrCache { System.out.println("sdrPWcache: Error " + e.toString()); throw new IOException(e.toString() + ": " + mPWcachedb); } catch (IOException e) { - System.out.println("Failed for file " + mPWcachedb + " " - + e.toString()); + System.out.println("Failed for file " + mPWcachedb + " " + e.toString()); throw new IOException(e.toString() + ": " + mPWcachedb); } catch (Exception e) { System.out.println("sdrPWcache: Error " + e.toString()); @@ -701,7 +696,7 @@ class PWsdrCache { while (enum1.hasMoreElements()) { String tag = (String) enum1.nextElement(); String pwd = (String) ht.get(tag); - + if (returnString == null) { returnString = tag + ":" + pwd + "\n"; } else { @@ -724,18 +719,19 @@ class PWsdrCache { if (colonIdx != -1) { String tag = line.substring(0, colonIdx); - String passwd = line.substring(colonIdx + 1, line.length()); + String passwd = line.substring(colonIdx + 1, + line.length()); ht.put(tag.trim(), passwd.trim()); } else { - // invalid format...log or throw...later + //invalid format...log or throw...later } } return ht; } /* - * get password from cache. This one supplies cache file name + * get password from cache. This one supplies cache file name */ public Password getEntry(String fileName, String tag) { mPWcachedb = fileName; @@ -743,8 +739,8 @@ class PWsdrCache { } /* - * if tag found with pwd, return it if tag not found, return null, which - * will cause it to give up + * if tag found with pwd, return it + * if tag not found, return null, which will cause it to give up */ public Password getEntry(String tag) { Hashtable pwTable = null; @@ -785,7 +781,7 @@ class PWsdrCache { } } - // copied from IOUtil.java + //copied from IOUtil.java /** * Checks if this is NT. */ @@ -819,17 +815,22 @@ class PWsdrCache { if (process.exitValue() == 0) { /** - * pOut = new BufferedReader( new - * InputStreamReader(process.getInputStream())); while ((l = - * pOut.readLine()) != null) { System.out.println(l); } + pOut = new BufferedReader( + new InputStreamReader(process.getInputStream())); + while ((l = pOut.readLine()) != null) { + System.out.println(l); + } **/ return true; } else { /** - * pOut = new BufferedReader( new - * InputStreamReader(process.getErrorStream())); l = null; while - * ((l = pOut.readLine()) != null) { System.out.println(l); } + pOut = new BufferedReader( + new InputStreamReader(process.getErrorStream())); + l = null; + while ((l = pOut.readLine()) != null) { + System.out.println(l); + } **/ return false; } @@ -873,11 +874,13 @@ class PWsdrCache { if (colonIdx != -1) { String tag = line.substring(0, colonIdx); - String passwd = line.substring(colonIdx + 1, line.length()); + String passwd = line.substring(colonIdx + 1, + line.length()); - debug(tag.trim() + " : " + passwd.trim()); + debug(tag.trim() + + " : " + passwd.trim()); } else { - // invalid format...log or throw...later + //invalid format...log or throw...later debug("invalid format"); } } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java index 10ca5b8c7..84cc54cbe 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCert.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; @@ -35,42 +36,43 @@ import netscape.security.x509.X500Name; import netscape.security.x509.X509CertImpl; import netscape.security.x509.X509CertInfo; + /** - * The PrettyPrintCert class is a utility program designed to "pretty print" a - * certificate. It assumes that the name of a data file is passed to the program - * via the command line, and that the contents contain a certificate encoded in - * an ASCII BASE 64 format. Note that the data file may contain an optional - * "-----BEGIN" header and/or an optional "-----END" trailer. - * + * The PrettyPrintCert class is a utility program designed to "pretty print" + * a certificate. It assumes that the name of a data file is passed to the + * program via the command line, and that the contents contain a certificate + * encoded in an ASCII BASE 64 format. Note that the data file may contain + * an optional "-----BEGIN" header and/or an optional "-----END" trailer. + * *

* The program may be invoked as follows: - * *

- * 
+ *
  *      PrettyPrintCert <input filename> [output filename]
- * 
+ *
  *      NOTE:  <input filename>   must contain an ASCII
  *                                BASE 64 encoded certificate
- * 
+ *
  *             <output filename>  contains a certificate displayed
  *                                in a "pretty print" ASCII format
  * 
- * + * * @version $Revision$, $Date$ */ public class PrettyPrintCert { // Define constants - public static final int ARGC = 2; + public static final int ARGC = 2; public static final String HEADER = "-----BEGIN"; public static final String TRAILER = "-----END"; public static void usageAndExit() { - System.out.println("Usage: PrettyPrintCert " + "[options] " - + " " + "[output filename]"); + System.out.println("Usage: PrettyPrintCert " + + "[options] " + + " " + + "[output filename]"); System.out.println("\n options: "); - System.out - .println(" -simpleinfo : prints limited cert info in easy to parse format"); + System.out.println(" -simpleinfo : prints limited cert info in easy to parse format"); System.exit(0); } @@ -85,7 +87,7 @@ public class PrettyPrintCert { CertPrettyPrint certDetails = null; String pp = new String(); FileOutputStream outputCert = null; - boolean mSimpleInfo = false; + boolean mSimpleInfo = false; String inputfile = null; String outputfile = null; @@ -128,68 +130,70 @@ public class PrettyPrintCert { if (inputfile == null) { usageAndExit(); } - + // (2) Create a DataInputStream() object to the BASE 64 - // encoded certificate contained within the file - // specified on the command line + // encoded certificate contained within the file + // specified on the command line try { inputCert = new BufferedReader(new InputStreamReader( - new BufferedInputStream(new FileInputStream(inputfile)))); + new BufferedInputStream( + new FileInputStream( + inputfile)))); } catch (FileNotFoundException e) { - System.out.println("PrettyPrintCert: can't find file " + inputfile - + ":\n" + e); + System.out.println("PrettyPrintCert: can't find file " + + inputfile + ":\n" + e); return; } // (3) Read the entire contents of the specified BASE 64 encoded - // certificate into a String() object throwing away any - // headers beginning with HEADER and any trailers beginning - // with TRAILER + // certificate into a String() object throwing away any + // headers beginning with HEADER and any trailers beginning + // with TRAILER try { while ((encodedBASE64CertChunk = inputCert.readLine()) != null) { - if (!(encodedBASE64CertChunk.startsWith(HEADER)) - && !(encodedBASE64CertChunk.startsWith(TRAILER))) { + if (!(encodedBASE64CertChunk.startsWith(HEADER)) && + !(encodedBASE64CertChunk.startsWith(TRAILER))) { encodedBASE64Cert += encodedBASE64CertChunk.trim(); } } } catch (IOException e) { - System.out.println("PrettyPrintCert: Unexpected BASE64 " - + "encoded error encountered in readLine():\n" + e); + System.out.println("PrettyPrintCert: Unexpected BASE64 " + + "encoded error encountered in readLine():\n" + + e); } // (4) Close the DataInputStream() object try { inputCert.close(); } catch (IOException e) { - System.out.println("PrettyPrintCert: Unexpected BASE64 " - + "encoded error encountered in close():\n" + e); + System.out.println("PrettyPrintCert: Unexpected BASE64 " + + "encoded error encountered in close():\n" + e); } - + // (5) Decode the ASCII BASE 64 certificate enclosed in the - // String() object into a BINARY BASE 64 byte[] object + // String() object into a BINARY BASE 64 byte[] object decodedBASE64Cert = com.netscape.osutil.OSUtil.AtoB(encodedBASE64Cert); // (6) Create an X509CertImpl() object from the BINARY BASE 64 - // byte[] object + // byte[] object try { cert = new X509CertImpl(decodedBASE64Cert); } catch (CertificateException e) { - System.out.println("PrettyPrintCert: Error encountered " - + "on parsing certificate :\n" + e); + System.out.println("PrettyPrintCert: Error encountered " + + "on parsing certificate :\n" + e); } if (mSimpleInfo) { try { X509CertInfo certinfo = (X509CertInfo) cert.get("x509.INFO"); - - CertificateSubjectName csn = (CertificateSubjectName) certinfo - .get(X509CertInfo.SUBJECT); + + CertificateSubjectName csn = (CertificateSubjectName) + certinfo.get(X509CertInfo.SUBJECT); Enumeration en = csn.getElements(); - X500Name dname = (X500Name) csn - .get(CertificateSubjectName.DN_NAME); + X500Name dname = (X500Name) csn.get(CertificateSubjectName.DN_NAME); pp = ""; RDN[] rdns = dname.getNames(); @@ -197,14 +201,14 @@ public class PrettyPrintCert { for (int i = rdns.length - 1; i >= 0; i--) { pp = pp + rdns[i] + "\n"; } - - } catch (Exception e) { + + } catch (Exception e) { System.out.println("ERROR"); e.printStackTrace(); - } + } } else { // (7) For this utility, always specify the default Locale - aLocale = Locale.getDefault(); + aLocale = Locale.getDefault(); // (8) Create a CertPrettyPrint() object certDetails = new CertPrettyPrint(cert); @@ -214,33 +218,34 @@ public class PrettyPrintCert { } // (10) Finally, "pretty print" the actual certificate to the console - // unless an output file has been specified + // unless an output file has been specified if (outputfile == null) { System.out.println(pp); } else { try { outputCert = new FileOutputStream(outputfile); } catch (Exception e) { - System.out.println("PrettyPrintCert: unable to open file " - + argv[1] + " for writing:\n" + e); + System.out.println("PrettyPrintCert: unable to open file " + + argv[1] + " for writing:\n" + e); return; } try { outputCert.write(pp.getBytes()); } catch (IOException e) { - System.out.println("PrettyPrintCert: Unexpected error " - + "encountered while attempting to write() " - + outputfile + ":\n" + e); + System.out.println("PrettyPrintCert: Unexpected error " + + "encountered while attempting to write() " + + outputfile + ":\n" + e); } try { outputCert.close(); } catch (IOException e) { - System.out.println("PrettyPrintCert: Unexpected error " - + "encountered while attempting to close() " - + outputfile + ":\n" + e); + System.out.println("PrettyPrintCert: Unexpected error " + + "encountered while attempting to close() " + + outputfile + ":\n" + e); } } } } + diff --git a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java index 9f9bfe437..b68f9fbc6 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/PrettyPrintCrl.java @@ -17,6 +17,7 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; @@ -37,33 +38,33 @@ import netscape.security.x509.OIDMap; import netscape.security.x509.X509CRLImpl; import netscape.security.x509.X509ExtensionException; + /** - * The PrettyPrintCrl class is a utility program designed to "pretty print" a - * CRL. It assumes that the name of a data file is passed to the program via the - * command line, and that the contents contain a CRL encoded in an ASCII BASE 64 - * format. Note that the data file may contain an optional "-----BEGIN" header - * and/or an optional "-----END" trailer. - * + * The PrettyPrintCrl class is a utility program designed to "pretty print" + * a CRL. It assumes that the name of a data file is passed to the + * program via the command line, and that the contents contain a CRL + * encoded in an ASCII BASE 64 format. Note that the data file may contain + * an optional "-----BEGIN" header and/or an optional "-----END" trailer. + * *

* The program may be invoked as follows: - * *

- * 
+ *
  *      PrettyPrintCrl <input filename> [output filename]
- * 
+ *
  *      NOTE:  <input filename>   must contain an ASCII
  *                                BASE 64 encoded CRL
- * 
+ *
  *             <output filename>  contains a CRL displayed
  *                                in a "pretty print" ASCII format
  * 
- * + * * @version $Revision$, $Date$ */ public class PrettyPrintCrl { // Define constants - public static final int ARGC = 2; + public static final int ARGC = 2; public static final String HEADER = "-----BEGIN"; public static final String TRAILER = "-----END"; @@ -81,90 +82,95 @@ public class PrettyPrintCrl { // (1) Check that at least one argument was submitted to the program if ((argv.length < 1) || (argv.length > ARGC)) { - System.out.println("Usage: PrettyPrintCrl " + " " - + "[output filename]"); + System.out.println("Usage: PrettyPrintCrl " + + " " + + "[output filename]"); return; } try { OIDMap.addAttribute(DeltaCRLIndicatorExtension.class.getName(), - DeltaCRLIndicatorExtension.OID, - DeltaCRLIndicatorExtension.NAME); + DeltaCRLIndicatorExtension.OID, + DeltaCRLIndicatorExtension.NAME); } catch (CertificateException e) { } try { OIDMap.addAttribute(HoldInstructionExtension.class.getName(), - HoldInstructionExtension.OID, HoldInstructionExtension.NAME); + HoldInstructionExtension.OID, + HoldInstructionExtension.NAME); } catch (CertificateException e) { } try { OIDMap.addAttribute(InvalidityDateExtension.class.getName(), - InvalidityDateExtension.OID, InvalidityDateExtension.NAME); + InvalidityDateExtension.OID, + InvalidityDateExtension.NAME); } catch (CertificateException e) { } try { - OIDMap.addAttribute( - IssuingDistributionPointExtension.class.getName(), - IssuingDistributionPointExtension.OID, - IssuingDistributionPointExtension.NAME); + OIDMap.addAttribute(IssuingDistributionPointExtension.class.getName(), + IssuingDistributionPointExtension.OID, + IssuingDistributionPointExtension.NAME); } catch (CertificateException e) { } // (2) Create a DataInputStream() object to the BASE 64 - // encoded CRL contained within the file - // specified on the command line + // encoded CRL contained within the file + // specified on the command line try { inputCrl = new BufferedReader(new InputStreamReader( - new BufferedInputStream(new FileInputStream(argv[0])))); + new BufferedInputStream( + new FileInputStream( + argv[0])))); } catch (FileNotFoundException e) { - System.out.println("PrettyPrintCrl(): can''t find file " + argv[0] - + ":\n" + e); + System.out.println("PrettyPrintCrl(): can''t find file " + + argv[0] + ":\n" + e); return; } // (3) Read the entire contents of the specified BASE 64 encoded - // CRL into a String() object throwing away any - // headers beginning with HEADER and any trailers beginning - // with TRAILER + // CRL into a String() object throwing away any + // headers beginning with HEADER and any trailers beginning + // with TRAILER try { while ((encodedBASE64CrlChunk = inputCrl.readLine()) != null) { - if (!(encodedBASE64CrlChunk.startsWith(HEADER)) - && !(encodedBASE64CrlChunk.startsWith(TRAILER))) { + if (!(encodedBASE64CrlChunk.startsWith(HEADER)) && + !(encodedBASE64CrlChunk.startsWith(TRAILER))) { encodedBASE64Crl += encodedBASE64CrlChunk.trim(); } } } catch (IOException e) { - System.out.println("PrettyPrintCrl(): Unexpected BASE64 " - + "encoded error encountered in readLine():\n" + e); + System.out.println("PrettyPrintCrl(): Unexpected BASE64 " + + "encoded error encountered in readLine():\n" + + e); } // (4) Close the DataInputStream() object try { inputCrl.close(); } catch (IOException e) { - System.out.println("PrettyPrintCrl(): Unexpected BASE64 " - + "encoded error encountered in close():\n" + e); + System.out.println("PrettyPrintCrl(): Unexpected BASE64 " + + "encoded error encountered in close():\n" + e); } - + // (5) Decode the ASCII BASE 64 CRL enclosed in the - // String() object into a BINARY BASE 64 byte[] object + // String() object into a BINARY BASE 64 byte[] object decodedBASE64Crl = com.netscape.osutil.OSUtil.AtoB(encodedBASE64Crl); // (6) Create an X509CRLImpl() object from the BINARY BASE 64 - // byte[] object + // byte[] object try { crl = new X509CRLImpl(decodedBASE64Crl); } catch (CRLException e) { - System.out.println("PrettyPrintCrl(): Error encountered " - + "on parsing and initialization errors:\n" + e); + System.out.println("PrettyPrintCrl(): Error encountered " + + "on parsing and initialization errors:\n" + e); } catch (X509ExtensionException e) { - System.out.println("PrettyPrintCrl(): Error encountered " - + "on parsing and initialization errors:\n" + e); + System.out.println("PrettyPrintCrl(): Error encountered " + + "on parsing and initialization errors:\n" + e); } // (7) For this utility, always specify the default Locale - aLocale = Locale.getDefault(); + aLocale = Locale.getDefault(); // (8) Create a CrlPrettyPrint() object CrlDetails = new CrlPrettyPrint(crl); @@ -173,32 +179,34 @@ public class PrettyPrintCrl { pp = CrlDetails.toString(aLocale); // (10) Finally, "pretty print" the actual CRL to the console - // unless an output file has been specified + // unless an output file has been specified if (argv.length != ARGC) { System.out.println(pp); } else { try { outputCrl = new FileOutputStream(argv[1]); } catch (IOException e) { - System.out.println("PrettyPrintCrl(): unable to open file " - + argv[1] + " for writing:\n" + e); + System.out.println("PrettyPrintCrl(): unable to open file " + + argv[1] + " for writing:\n" + e); return; } try { outputCrl.write(pp.getBytes()); } catch (IOException e) { - System.out.println("PrettyPrintCrl(): I/O error " - + "encountered during write():\n" + e); + System.out.println("PrettyPrintCrl(): I/O error " + + "encountered during write():\n" + + e); } try { outputCrl.close(); } catch (IOException e) { - System.out.println("PrettyPrintCrl(): Unexpected error " - + "encountered while attempting to close() " + argv[1] - + ":\n" + e); + System.out.println("PrettyPrintCrl(): Unexpected error " + + "encountered while attempting to close() " + + argv[1] + ":\n" + e); } } } } + diff --git a/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java b/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java index 553062ace..d43b35337 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/TestCRLSigning.java @@ -34,18 +34,19 @@ import org.mozilla.jss.util.Password; /** * Tool used to test out signing a CRL - * + * *

- * * @version $Revision$ Date: $ */ -public class TestCRLSigning { - public static void printUsage() { - System.out - .println("Command "); +public class TestCRLSigning +{ + public static void printUsage() + { + System.out.println("Command "); } - public static void main(String args[]) throws Exception { + public static void main(String args[]) throws Exception + { String dir = args[0]; String num = args[1]; String keysize = args[2]; @@ -54,19 +55,19 @@ public class TestCRLSigning { // initialize JSS CryptoManager cm = null; - CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues( - dir, "", "", "secmod.db"); + CryptoManager.InitializationValues vals = + new CryptoManager.InitializationValues(dir, "", "", "secmod.db"); CryptoManager.initialize(vals); cm = CryptoManager.getInstance(); - // Login to token + // Login to token CryptoToken token = null; if (tokenname.equals("internal")) { - token = cm.getInternalKeyStorageToken(); + token = cm.getInternalKeyStorageToken(); } else { - token = cm.getTokenByName(tokenname); + token = cm.getTokenByName(tokenname); } - Password pass = new Password(tokenpwd.toCharArray()); + Password pass = new Password(tokenpwd.toCharArray()); token.login(pass); // generate key pair @@ -80,16 +81,22 @@ public class TestCRLSigning { Hashtable badCerts = new Hashtable(); int n = Integer.parseInt(num); for (int i = 0; i < n; i++) { - badCerts.put(Integer.toString(i), new RevokedCertImpl( - new BigInteger(Integer.toString(i)), curDate)); + badCerts.put(Integer.toString(i), + new RevokedCertImpl(new BigInteger(Integer.toString(i)), curDate)); } long endPutting = System.currentTimeMillis(); long startConstructing = System.currentTimeMillis(); - X509CRLImpl crl = new X509CRLImpl(new X500Name("CN=Signer"), null, - curDate, curDate, badCerts, null); + X509CRLImpl crl = new X509CRLImpl( + new X500Name("CN=Signer"), + null, + curDate, + curDate, + badCerts, + null); long endConstructing = System.currentTimeMillis(); + System.out.println("Start signing"); long startSigning = System.currentTimeMillis(); crl.sign(pair.getPrivate(), "SHA1withRSA"); @@ -101,14 +108,10 @@ public class TestCRLSigning { long endData = System.currentTimeMillis(); System.out.println("Summary:"); - System.out.println("Insertion time (ms): " - + Long.toString(endPutting - startPutting)); - System.out.println("Construction time (ms): " - + Long.toString(endConstructing - startConstructing)); - System.out.println("Signing time (ms): " - + Long.toString(endSigning - startSigning)); - System.out.println("Data time (ms): " - + Long.toString(endData - startData)); + System.out.println("Insertion time (ms): " + Long.toString(endPutting - startPutting)); + System.out.println("Construction time (ms): " + Long.toString(endConstructing - startConstructing)); + System.out.println("Signing time (ms): " + Long.toString(endSigning - startSigning)); + System.out.println("Data time (ms): " + Long.toString(endData - startData)); System.out.println("Data size (bytes): " + Long.toString(data.length)); } } diff --git a/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java b/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java index ee7a3fe3e..ade2b4679 100644 --- a/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java +++ b/pki/base/java-tools/src/com/netscape/cmstools/TokenInfo.java @@ -17,58 +17,59 @@ // --- END COPYRIGHT BLOCK --- package com.netscape.cmstools; + import java.util.Enumeration; import org.mozilla.jss.CryptoManager; import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.pkcs11.PK11Module; + + /** * Tool used to determine which external hardware tokens are visible to the * Certificate System subsystem. This can be used to diagnose whether problems * using tokens are related to the Certificate System being unable to detect it. - * + * *

- * * @version $Revision$ Date: $ */ public class TokenInfo { - + /** - * Creates a new instance of CMCRevoke. + * Creates a new instance of CMCRevoke. */ - public static void main(String[] args) { + public static void main(String[]args) { try { - if (args.length != 1) { - System.out.println("Usage: TokenInfo "); - System.exit(0); - } - System.out.println("Database Path: " + args[0]); + if (args.length != 1) { + System.out.println("Usage: TokenInfo "); + System.exit(0); + } + System.out.println("Database Path: " + args[0]); - CryptoManager.InitializationValues vals = new CryptoManager.InitializationValues( - args[0], "", "", "secmod.db"); + CryptoManager.InitializationValues vals = + new CryptoManager.InitializationValues(args[0], + "", "", "secmod.db"); - CryptoManager.initialize(vals); + CryptoManager.initialize(vals); + + CryptoManager cm = CryptoManager.getInstance(); + Enumeration modules = cm.getModules(); + while (modules.hasMoreElements()) { + PK11Module m = (PK11Module)modules.nextElement(); + System.out.println("Found external module '" + m.getName() + "'"); + } + Enumeration tokens = cm.getExternalTokens(); - CryptoManager cm = CryptoManager.getInstance(); - Enumeration modules = cm.getModules(); - while (modules.hasMoreElements()) { - PK11Module m = (PK11Module) modules.nextElement(); - System.out.println("Found external module '" + m.getName() - + "'"); - } - Enumeration tokens = cm.getExternalTokens(); + while (tokens.hasMoreElements()) { + CryptoToken t = (CryptoToken)tokens.nextElement(); + System.out.println("Found external token '" + t.getName() + "'"); + } - while (tokens.hasMoreElements()) { - CryptoToken t = (CryptoToken) tokens.nextElement(); - System.out - .println("Found external token '" + t.getName() + "'"); + }catch (Exception e) { + e.printStackTrace(); + System.exit(1); } - - } catch (Exception e) { - e.printStackTrace(); - System.exit(1); - } - + } } -- cgit