How to renew a self-signed openssl PEM certificate

假如想象 提交于 2019-12-03 14:29:23

I create a bash script to solve question of renew expiry date of a certification PEM file

#!/bin/bash

# FIXME we need shttp.pem are on same folder like execution path of script
# Extract a certificate sign request form certification file (PEM)
openssl x509 -x509toreq -in shttpd.pem -out shttpd.csr -signkey shttpd.pem
# Extract private key from certification file (PEM)
openssl rsa -in shttpd.pem -out shttpd.key
# Create new certification for ten years
openssl x509 -req -days 3650 -in shttpd.csr -out shttpd.crt.new -signkey shttpd.key 
#Concatenate new certificate and old private key on a renewed pem file
cat shttpd.crt.new shttpd.key > shttpd.pem.new

More user friendly version of jorge dominguez script

#!/bin/sh
: '
Script used to renew self-signed certificate saved as PEM
1st arg - current PEM file
rest args - options for openssl x509 -req

new PEM is saved in same directory as old one with .new appendix

example usage: ./pemrenew.sh /tmp/keycert.pem -days 365
'

# First arg is pointed to current PEM file
pem_file="$1"
shift

# Create temporary files
tmp_csr=$(mktemp /tmp/csr.XXXXXXXXX)
tmp_key=$(mktemp /tmp/key.XXXXXXXXX)
tmp_crt=$(mktemp /tmp/crt.XXXXXXXXX)

# Extract a certificate sign request form certification file (PEM)
openssl x509 -x509toreq -in $pem_file -out $tmp_csr -signkey $pem_file
# Extract private key from certification file (PEM)
openssl rsa -in $pem_file -out $tmp_key
# Create new certificate with provided options as arguments
openssl x509 -req $@ -in $tmp_csr -out $tmp_crt -signkey $tmp_key

# Merge certificate and key to one file
cat $tmp_crt $tmp_key > $pem_file.new

# Clean temporary files
rm $tmp_csr $tmp_key $tmp_crt

The following command creates a relatively strong (as of 2019) certificate for the domain example.com that is valid for 3650 days (~10 years). It saves the private key into example.key and certificate into example.crt.

openssl req -x509 -newkey rsa:4096 -sha256 -nodes -keyout example.key -out example.crt -subj "/CN=example.com" -days 3650

For more information, see: How to create a self-signed certificate with OpenSSL

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!