Skip to content

Instantly share code, notes, and snippets.

@ggrandes
Last active November 26, 2019 19:48
Show Gist options
  • Save ggrandes/aa5b119eba2d90b4f13d to your computer and use it in GitHub Desktop.
Save ggrandes/aa5b119eba2d90b4f13d to your computer and use it in GitHub Desktop.
Generate X.509 Certificate (Server/Client/Mail) with OpenSSL - Linux
#!/bin/bash
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Original Source:
# https://gist.github.com/ggrandes/aa5b119eba2d90b4f13d
#
CA_CN="${CA_CN:-CA-TEST}"
CA_OU="${CA_OU:-TEST}"
CN="${CN:-USER-TEST}"
OU="${OU:-TEST}"
# Self-Signed
[ ! -s "ca.crt" ] &&
openssl req -new -x509 -batch -newkey rsa:2048 -nodes \
-keyout ca.key -out ca.crt \
-days $[365 * 5 + 1] -set_serial $(date +%s) \
-config /dev/stdin <<END
[ req ]
x509_extensions = v3_ca
string_mask = nombstr
distinguished_name = req_distinguished_name
prompt = no
encrypt_key = no
default_md = sha256
[ req_distinguished_name ]
CN = ${CA_CN}
OU = ${CA_OU}
[ v3_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer:always
basicConstraints = critical, CA:TRUE, pathlen:0
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment, keyCertSign
extendedKeyUsage = clientAuth, serverAuth, emailProtection
nsCertType = client, server, email, sslCA, emailCA
END
# Sign certificate
[ ! -s "user.crt" ] &&
openssl req -new -sha256 -batch -newkey rsa:2048 -nodes \
-keyout user.key -out user.req -subj "/CN=${CN}/OU=${OU}" &&
openssl x509 -req -sha256 -in user.req -CA ca.crt -CAkey ca.key -out user.crt \
-days $[365 * 5 + 1] -set_serial $(date +%s) \
-extfile /dev/stdin -extensions v3_ext <<"END"
[ v3_ext ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always, issuer:always
basicConstraints = critical, CA:FALSE
keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment
extendedKeyUsage = clientAuth, serverAuth, emailProtection
nsCertType = client, server, email
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment