title: Can a Certificate be generated in Java, without using sun internal code, keytool, or bouncycastle
body: <p>I am trying to generate a certificate that can be used with an SSL/TLS socket on a network application (find more info <a href="https://security.stackexchange.com/questions/76959/what-is-the-security-value-of-this-on-the-fly-user-registration">here</a>). </p>
  
  <p>I have generated an RSA 1024-bit KeyPair with</p>
  
  <pre><code>public KeyPair generateKeyPair(final String algorithm, final int bitLength) throws 
      NoSuchAlgorithmException {
      final KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm);
      generator.initialize(bitLength);
      return generator.generateKeyPair();
  }
  </code></pre>
  
  <p>And trying to generate the certificate with </p>
  
  <pre><code>private static Certificate generateCertificate(final PublicKey publicKey) throws 
      CertificateException {
      X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey.getEncoded());
      final ByteArrayInputStream bais = new ByteArrayInputStream(spec.getEncoded());
  
      final CertificateFactory factory = CertificateFactory.getInstance("X.509");
      final Certificate cert = factory.generateCertificate(bais);
      return cert;
  }
  </code></pre>
  
  <p>but doing this gives me a </p>
  
  <pre><code>java.security.cert.CertificateException: Unable to initialize, java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big.
  at sun.security.x509.X509CertImpl.&lt;init&gt;(Unknown Source)
  at sun.security.provider.X509Factory.engineGenerateCertificate(Unknown Source)
  at java.security.cert.CertificateFactory.generateCertificate(Unknown Source)
  at net.zephyrion.ssl.SSLServer.generateCertificate(SSLServer.java:123)
  at net.zephyrion.ssl.SSLServer.processKeyStore(SSLServer.java:86)
  at net.zephyrion.ssl.SSLServer.main(SSLServer.java:41)
  Caused by: java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big.
  at sun.security.util.DerInputStream.getLength(Unknown Source)
  at sun.security.util.DerValue.&lt;init&gt;(Unknown Source)
  at sun.security.util.DerInputStream.getDerValue(Unknown Source)
  at sun.security.x509.X509CertImpl.parse(Unknown Source)
  ... 6 more
  </code></pre>
  
  <p>I've looked around, and the last answer about this was in 2009. I want it to be as lightweight as possible, so I don't want to use bouncycastle, and I want it to use pure public Java API, so no sun internal code, and I don't want to use an external process, so not keytool.</p>
  
  <p>I am using Java 7 for this until Java 8 is released publicly, but even then, would the framework be available to do this?</p>