Skip to content

Instantly share code, notes, and snippets.

@aschwinwester
Last active May 6, 2022 08:54
Show Gist options
  • Save aschwinwester/caf147377894c58c236fc1313a0783de to your computer and use it in GitHub Desktop.
Save aschwinwester/caf147377894c58c236fc1313a0783de to your computer and use it in GitHub Desktop.
openssl x509 and pkcs12 tips

CLI tips for openssl

Some commands I used often

X509

Create CSR with new key

This will not encrypt the private key. It uses the configuration file

openssl req -utf8 -nodes -sha256 \ 
    -newkey rsa:2048 -keyout my_private.key -out my_csr.csr \
    -config ./configuration.txt

sample configuration file

[ req ]
distinguished_name = req_distinguished_name
req_extensions    = req_ext
prompt = no
[ req_distinguished_name ]
countryName                 = NL
stateOrProvinceName         = Limburg
organizationName            = My Company N.V.
commonName                  = api.savings.nl.eu.mycompany.com
organizationalUnitName      = Mobile Apps & Rust Dev
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1   = api.savings.nl.eu.mycompany.com

optional items in de configuration.txt are:

[ req ]
default_bits = 4096
default_md = sha256
string_mask = utf8only

if you don't use the -nodes option, your private key will also be encrypted. Output is PEM.

openssl req -newkey rsa:2048 -keyout my_private.key -out my_csr.csr \
    -config ./configuration.txt

Create CSR with existing key

This is usefull for renewal of certifcate which will expire output is PEM.

openssl req -utf8 -new -key key.pem -out my_csr.csr

PKCS12

Export the private key from pkcs12 format keystore

openssl pkcs12 -in keystore_name.p12 -nodes -nocerts -out private.key

Export the public certificate from pkcs12 format keystore

openssl pkcs12 -in keystore_name.p12 -nokeys -out public-cert-file

List certificates on pkcs12

openssl pkcs12 -nokeys -info \
    -in my_pkcs12_file \
    -passin pass:<pfx's password>

Create pkcs12 with alias

Spring boot needs an alias for searching the correct certificate.

openssl pkcs12 -export -out ./my_pkcs12.p12 \
    -inkey ./my_private.key -in ./my_cert.crt \ 
    -name "server" \
    -certfile my_intermediate_cert.pem

NOTE: You can only provide option -certfile ones. So you can combine the root CA and intermediate ca in one file:

cat root_ca.pem intermediate_ca.pem > combined.pem

Verify using keytool

keytool -list -v -keystore my_pkcs12.p12 -alias server
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment