Search code examples
javax509

get .cer file with bouncy castel in java


I had to generate x509 self-signed certificate How can one distract sertificate and private key file from this code? Is it possible? Are there other ways how to generate x509 self-signed certificate? Please help me.

import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.security.auth.x500.X500Principal;
import org.bouncycastle.asn1.x509.BasicConstraints;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.GeneralName;
import org.bouncycastle.asn1.x509.GeneralNames;
import org.bouncycastle.asn1.x509.KeyPurposeId;
import org.bouncycastle.asn1.x509.KeyUsage;
import org.bouncycastle.asn1.x509.X509Extensions;
import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
import org.bouncycastle.x509.X509V3CertificateGenerator;

public class javaskods {
  public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException,
  NoSuchProviderException, SignatureException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 10000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 10000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature
    | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(
    KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(
    new GeneralName(GeneralName.rfc822Name, "[email protected]")));
return certGen.generateX509Certificate(pair.getPrivate(), "BC");
  }

  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());   
    KeyPair pair = generateRSAKeyPair();
    X509Certificate cert = generateV3Certificate(pair);
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());
  }
  public static KeyPair generateRSAKeyPair() throws Exception {
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
    kpGen.initialize(1024, new SecureRandom());   
    return kpGen.generateKeyPair();
  }
}

Solution

  • You can generate a self-signed certificates using keytool (part of JDK) or with other utilities.

    Java Keytool: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/keytool.html

    Keytool-ui: https://code.google.com/p/keytool-iui/

    keytool -genkey -keystore ./myjks -keyalg RSA -keysize 2048 -validity 999 -alias mykey
    

    This will create a new private key for you in the myjks file.

    Then in your code you can refer to the certificate via alias name and jks file.

    If you are encrypting, you will want to use keytool to export the public key and share it with the recipient of the encrypted data.

    keytool -export -keystore ./myjks -file mykey_pub.cer -alias mykey
    

    The above command will export a certificate which contains the public key.