ExportCert.java

/*
** Module   : ExportCert.java
** Abstract : export a certificate and its private key into a JKS store.
**
** Copyright (c) 2021, Golden Code Development Corporation.
**
** -#- -I- --Date-- ---------------------------------------Description----------------------------------------
** 001 CA  20211012 Created the initial version.
*/

/*
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU Affero General Public License as
** published by the Free Software Foundation, either version 3 of the
** License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU Affero General Public License for more details.
**
** You may find a copy of the GNU Affero GPL version 3 at the following
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
** 
** Additional terms under GNU Affero GPL version 3 section 7:
** 
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
**   terms apply to the works covered under the License.  These additional terms
**   are non-permissive additional terms allowed under Section 7 of the GNU
**   Affero GPL version 3 and may not be removed by you.
** 
**   0. Attribution Requirement.
** 
**     You must preserve all legal notices or author attributions in the covered
**     work or Appropriate Legal Notices displayed by works containing the covered
**     work.  You may not remove from the covered work any author or developer
**     credit already included within the covered work.
** 
**   1. No License To Use Trademarks.
** 
**     This license does not grant any license or rights to use the trademarks
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
**     of Golden Code Development Corporation. You are not authorized to use the
**     name Golden Code, FWD, or the names of any author or contributor, for
**     publicity purposes without written authorization.
** 
**   2. No Misrepresentation of Affiliation.
** 
**     You may not represent yourself as Golden Code Development Corporation or FWD.
** 
**     You may not represent yourself for publicity purposes as associated with
**     Golden Code Development Corporation, FWD, or any author or contributor to
**     the covered work, without written authorization.
** 
**   3. No Misrepresentation of Source or Origin.
** 
**     You may not represent the covered work as solely your work.  All modified
**     versions of the covered work must be marked in a reasonable way to make it
**     clear that the modified work is not originating from Golden Code Development
**     Corporation or FWD.  All modified versions must contain the notices of
**     attribution required in this license.
*/

package com.goldencode.p2j.util;

import java.io.*;
import java.security.*;
import java.security.cert.*;

import com.goldencode.p2j.cfg.*;
import com.goldencode.p2j.directory.*;
import com.goldencode.p2j.security.*;

/**
 * Export the certificate and its private key from the directory.
 * <p>
 * This tool requires that the private key is saved in the directory, with its encryption password.
 * <p>
 * The store name will be <code>alias-private-key.store</code>, where <code>alias</code> is the certificate 
 * alias to be exported.
 */
public class ExportCert
{
   /**
    * Export the certificate and its private key.
    * 
    * @param    dir
    *           The instance of directory to read from.
    * @param    alias
    *           The certificate alias.
    * @param    storePassword
    *           The password to use for the created store.
    * @param    keyEntryPassword
    *           The password to use for the key-entry in the store.
    * 
    * @throws   Exception
    *           In case of errors.
    */
   private static void exportCertificate(DirectoryService dir, 
                                         String           alias, 
                                         String           storePassword, 
                                         String           keyEntryPassword)
   throws Exception
   {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      SSLCertFactory factory = SSLCertGenUtil.getFactory();
      
      String filename = alias + "-private-key.store";
      
      String[] rootCAs = dir.enumerateNodes("/security/certificates/cas");
      X509Certificate[] chain = new X509Certificate[rootCAs.length + 1];
      
      // alias
      byte[] data = dir.getNodeByteArray("/security/certificates/peers/" + alias, "value");
      ByteArrayInputStream bis = new ByteArrayInputStream(data);
      chain[0] = (X509Certificate) cf.generateCertificate(bis);
      
      // root CA chain
      for (int i = 0; i < rootCAs.length; i++)
      {
         data = dir.getNodeByteArray("/security/certificates/cas/" + rootCAs[i], "value");
         bis = new ByteArrayInputStream(data);
         chain[i + 1] = (X509Certificate) cf.generateCertificate(bis);
      }
      
      String path = "/security/certificates/private-keys/";
      byte[] dataPK = dir.getNodeByteArray(path + alias + "/key-entry", "value");
      byte[] dataPW = dir.getNodeByteArray(path + alias + "/key-password", "value");
      PrivateKey privateKey = factory.decryptPrivateKey(dataPK, new String(dataPW));
      
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(null, null);
      ks.setKeyEntry(alias, privateKey, keyEntryPassword.toCharArray(), chain);
      ks.store(new FileOutputStream(new File(filename)), storePassword.toCharArray());
   }

   /**
    * Command line driver.
    * 
    * @param    args
    *           Application command line parameters.
    *
    * @throws   Exception
    *           In case of errors.
    */
   public static void main(String[] args) 
   throws Exception
   {
      if (!(args.length == 5 || args.length == 3))
      {
         System.out.println("usage: java ExportCert [<config.xml> { <password> | - } ] " + 
                            "alias store-password entry-password");
         return;
      }
      
      BootstrapConfig bc = null;
      char[] pass  = null;
      String conf  = null;
      int start = 0;

      if (args[0].endsWith(".xml"))
      {
         conf = args[0];
         start = 2;
         
         if (!args[1].equals("-"))
         {
            pass = args[1].toCharArray();
         }
      }
      else
      {
         conf = "standard_server.xml";
      }
      
      bc = new BootstrapConfig(conf, pass, null, null);
      System.out.println("Instantiating DirectoryService");
      DirectoryService dir = DirectoryService.createInstance(bc);
      System.out.println("DirectoryService is up");

      System.out.println("Binding to directory.");
      if (!dir.bind())
      {
         throw new RuntimeException("bind() failed");
      }
      
      System.out.println("Bound to directory.");

      String alias = args[start++];
      String storePassword = args[start++];
      String keyEntryPassword = args[start++];
      
      exportCertificate(dir, alias, storePassword, keyEntryPassword);
   
      System.out.println("Unbinding from directory...");
      if (!dir.unbind())
      {
         throw new RuntimeException("unbind() failed");
      }
      System.out.println("Unbound.");
 
      System.out.println("Done.");
   }
}