title: Generate certificate chain in java
body: <p>The question is how to generate certificate chains programmatically in Java. In other words, I would like to perform in java the operations detailed here: <a href="http://fusesource.com/docs/broker/5.3/security/i382664.html">http://fusesource.com/docs/broker/5.3/security/i382664.html</a></p>
  
  <p>Besically, I can create the RSA keys for a new client:</p>
  
  <pre><code>private KeyPair genRSAKeyPair(){
      // Get RSA key factory:
      KeyPairGenerator kpg = null;
      try {
          kpg = KeyPairGenerator.getInstance("RSA");
      } catch (NoSuchAlgorithmException e) {
          log.error(e.getMessage());
          e.printStackTrace();
          return null;
      }
      // Generate RSA public/private key pair:
      kpg.initialize(RSA_KEY_LEN);
      KeyPair kp = kpg.genKeyPair();
      return kp;
  </code></pre>
  
  <p>}</p>
  
  <p>and I generate the corresponding certificate:</p>
  
  <pre><code>private X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
    throws GeneralSecurityException, IOException  {
      PrivateKey privkey = pair.getPrivate();
      X509CertInfo info = new X509CertInfo();
      Date from = new Date();
      Date to = new Date(from.getTime() + days * 86400000l);
      CertificateValidity interval = new CertificateValidity(from, to);
      BigInteger sn = new BigInteger(64, new SecureRandom());
      X500Name owner = new X500Name(dn);
  
      info.set(X509CertInfo.VALIDITY, interval);
      info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
      info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
      info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
      info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
      info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
      AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
      info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
  
      // Sign the cert to identify the algorithm that's used.
      X509CertImpl cert = new X509CertImpl(info);
      cert.sign(privkey, algorithm);
  
      // Update the algorith, and resign.
      algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
      info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
      cert = new X509CertImpl(info);
      cert.sign(privkey, algorithm);
      return cert;
  </code></pre>
  
  <p>}</p>
  
  <p>Then I generate the cert signing request and I save it to csrFile file:</p>
  
  <pre><code>public static void writeCertReq(File csrFile, String alias, String keyPass, KeyStore ks) 
          throws KeyStoreException, 
                 NoSuchAlgorithmException, 
                 InvalidKeyException, 
                 IOException, 
                 CertificateException, 
                 SignatureException, 
                 UnrecoverableKeyException {
  
      Object objs[] = getPrivateKey(ks, alias, keyPass.toCharArray());
      PrivateKey privKey = (PrivateKey) objs[0];
  
      PKCS10 request = null;
  
      Certificate cert = ks.getCertificate(alias);
      request = new PKCS10(cert.getPublicKey());
      String sigAlgName = "MD5WithRSA";
      Signature signature = Signature.getInstance(sigAlgName);
      signature.initSign(privKey);
      X500Name subject = new X500Name(((X509Certificate) cert).getSubjectDN().toString());
      X500Signer signer = new X500Signer(signature, subject);
      request.encodeAndSign(signer);
      request.print(System.out);
      FileOutputStream fos = new FileOutputStream(csrFile);
      PrintStream ps = new PrintStream(fos);
      request.print(ps);
      fos.close();
  }
  </code></pre>
  
  <p>where</p>
  
  <pre><code>private static Object[] getPrivateKey(KeyStore ks, String alias, char keyPass[]) 
          throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
      key = null;        
      key = ks.getKey(alias, keyPass);
      return (new Object[]{ (PrivateKey) key, keyPass });
  }
  </code></pre>
  
  <p>Now I should sign the CSR with the CA private key, but I cannot see how to achive that in java. I have "my own" CA private key in my jks. </p>
  
  <p>Besides, once I manage to sign the CSR I should chain the CA cert with the signed CSR: how that can be done in java?</p>
  
  <p>I would prefer not to use bc or other external libs, just "sun.security" classes.</p>
  
  <p>Thank you.</p>