Wednesday, October 26, 2016

Create self signed certification in linux with java keytool

#!/bin/bash
export PW=`cat password`

# Create a self signed key pair root CA certificate.
keytool -genkeypair -v \
-alias testca \
-dname "CN=testca, OU=Dev, O=inBay, L=Ottawa, ST=ON, C=CA" \
-keystore testca.jks \
-keypass:env PW \
-storepass:env PW \
-keyalg RSA \
-keysize 4096 \
-ext KeyUsage:critical="keyCertSign" \
-ext BasicConstraints:critical="ca:true" \
-validity 9999


# Export the exampleCA public certificate
keytool -export -v \
-alias testca \
-file testca.crt \
-keypass:env PW \
-storepass:env PW \
-keystore testca.jks \
-rfc

# Create a server certificate,
keytool -genkeypair -v \
  -alias localhost \
  -dname "CN=127.0.0.1, OU=Dev, O=inBay, L=Ottawa, ST=ON, C=CA" \
  -keystore localhost.jks \
  -keypass:env PW \
  -storepass:env PW \
  -keyalg RSA \
  -keysize 2048 \
  -validity 3650

# Create a certificate signing request
keytool -certreq -v \
  -alias localhost \
  -keypass:env PW \
  -storepass:env PW \
  -keystore localhost.jks \
  -file localhost.csr


# Tell testca to sign the localhost certificate. Note the extension is on the request, not the
# original certificate.
# Technically, keyUsage should be digitalSignature for DHE or ECDHE, keyEncipherment for RSA.

keytool -gencert -v \
  -alias testca \
  -keypass:env PW \
  -storepass:env PW \
  -keystore testca.jks \
  -infile localhost.csr \
  -outfile localhost.crt \
  -ext KeyUsage:critical="digitalSignature,keyEncipherment" \
  -ext EKU="serverAuth" \
  -rfc

# Tell localhost.jks it can trust testca as a signer.
keytool -import -v \
  -alias testca \
  -file testca.crt \
  -keystore localhost.jks \
  -storetype JKS \
  -storepass:env PW << EOF
yes
EOF

# Import the signed certificate back into localhost.jks
keytool -import -v \
  -alias localhost \
  -file localhost.crt \
  -keystore localhost.jks \
  -storetype JKS \
  -storepass:env PW

# List out the contents of localhost.jks just to confirm it.
# If you are using Play as a TLS termination point, this is the key store you should present as the server.
keytool -list -v \
  -keystore localhost.jks \
  -storepass:env PW

#First export key

keytool -importkeystore -srckeystore localhost.jks -destkeystore keystore.p12 -deststoretype PKCS12

#For apache ssl certificate file you need certificate only

openssl pkcs12 -in keystore.p12 -nokeys -out localserver.crt
#or ssl key file you need only keys
openssl pkcs12 -in keystore.p12 -nocerts -nodes -out localserver.key



No comments:

Post a Comment