Back
Featured image of post OpenSSL снипет

OpenSSL снипет

Генерируем CA, и подписываем им TLS ECDSA ключ испоьлзуя OpenSSL

Здесь очень много полезных команд, но полную работоспособность проверять лень 😄

#!/usr/bin/env sh
set -e

# path to private part of CA (PEM encoded)
CA_KEY='ca.key'
# path to public part of CA (PEM encoded)
CA_CRT='ca.crt'
# password to use CA
CA_PASSWORD='longalphanum'

# Country
C='UA'
# State
ST='Kiev'
# Location
L='Kiev'
# Organization
O='No organization'
# Organization unit
OU='No unit'
# Domain to issue final cert for
DOMAIN='vlasov.pro'
# Days while the certificate will be valid
DAYS='365'

subj() {
  echo "/C=${C}/ST=${ST}/L=${L}/O=${O}/OU=${OU}/CN=$1"
}

if [ ! -f "$CA_KEY" ] || [ "$1" = '-ca' ]; then
  echo 'basicConstraints=CA:true' > extfile.txt
  # CA - used for signing of both server and client certs
  # generate private key
  openssl ecparam -genkey -name prime256v1 | openssl ec -out "$CA_KEY"
  # generate signing request
  openssl req -new -key "$CA_KEY" -out ca.csr -subj "$(subj "$O CA")"
  # csr + key = crt
  openssl x509 -req -days 3650 -in ca.csr -signkey "$CA_KEY" -extfile extfile.txt -out "$CA_CRT"
  rm -f ca.csr
  # convert crt to DER format
  openssl x509 -inform PEM -outform DER -in "$CA_CRT" -out "$CA_CRT.der"
  echo 'Generated CA'
fi

# generate and sign certificate
  cat <<EOF >extfile.txt
[ req ]
req_extensions     = req_ext
distinguished_name = req_distinguished_name

[req_distinguished_name]

[ req_ext ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1   = $DOMAIN
DNS.2   = *.$DOMAIN
EOF
  # issue
  openssl ecparam -genkey -name prime256v1 | openssl ec -out "${DOMAIN}.key"  # key
  openssl req -new -key "${DOMAIN}.key" -out "${DOMAIN}.csr" -config extfile.txt -subj "$(subj $DOMAIN)" # csr
  openssl x509 -req \
    -days "$DAYS" \
    -in "${DOMAIN}.csr" \
    -CA "$CA_CRT" \
    -out "${DOMAIN}.crt" \
    -CAkey "$CA_KEY" \
    -CAcreateserial \
    -passin "pass:$CA_PASSWORD" \
    -extensions req_ext -extfile extfile.txt  # csr + rootCA.crt = crt 
  rm -f "${DOMAIN}.csr"
  # convert DER -> PEM
  openssl x509 -inform PEM -outform DER -in "${DOMAIN}.crt" -out "${DOMAIN}.der.crt"  # convert
  # convert PEM -> pkcs12
  openssl pkcs12 -export \
    -inkey "${DOMAIN}.key" \
    -in "${DOMAIN}.crt" \
    -out "${DOMAIN}.pfx" \
    -password "pass:$JKS_PASSWORD" \
    -name "$DOMAIN"
  # create fullchain
  cat "${DOMAIN}.crt" "$CA_CRT" > "${DOMAIN}.full"
  # verify
  openssl verify -CAfile "$CA_CRT" "${DOMAIN}.crt"
  # info
  log_info "Generated $DOMAIN"
done
rm -f extfile.txt
Licensed under Apache License, Version 2.0
Обновлено Jul 27, 2021 15:53 +0300
comments powered by Disqus
All rights reserved
Создано при помощи Hugo
Тема Stack, дизайн Jimmy