OpenSSL and implementation of private CA to realize certificate application issuing

2 OpenSSL

OpenSSL is an open source software library package, which can be used by applications to communicate securely, avoid eavesdropping, and confirm the identity of the other end of the connection. This package is widely used in web servers on the Internet
The main library is written in C language, which realizes the basic encryption function, SSL and TLS protocol. OpenSSL can run on OpenVMS, Microsoft Windows and most Unix like operating systems (including Solaris, Linux, Mac OS X and various versions of open source BSD operating systems)
OpenSSL started in 1998 with the goal of inventing a free encryption tool for use on the Internet. OpenSSL is based on SSLeay developed by Eric young and Tim Hudson. With the two working for RSA, SSLeay stopped development in December 1998. Therefore, in December 1998, OpenSSL was branched out of the community and continued to be developed
The OpenSSL management board is currently made up of 7 people with 13 developers [3] who have submit rights (many of whom are also part of the OpenSSL management board). There are only two full-time employees (researchers) and the rest are volunteers
The annual budget of the project is less than US $1 million, which mainly depends on donations. TLS 1.3 development sponsored by Akamai
Bleeding heart vulnerability: OpenSSL version 1.0.1 (excluding 1.0.1g) contains a critical vulnerability that allows attackers to read memory information from the server. The vulnerability was made public in April 2014, affecting two-thirds of active websites
There are three components:
1.libcrypto: a library for encryption and decryption
2.libssl: a security library for ssl communication protocol
3.openssl: a multi-purpose command line tool

2.2 Base64 encoding

Base64 is one of the most common encoding methods used to transmit 8Bit bytecode on the network. Base64 is a method to represent binary data based on 64 printable characters

The encoding process of base64 is as follows:
Put every 3 bytes into a 24 bit buffer. If there are less than 3 bytes, the rest of the buffer will be filled with 0. Then take out 6 bits each time (the 6th power of 2 is 64, and use 64 characters to represent all), fill the high 2 bits with 0, form a new byte, calculate the decimal value of the new byte, correspond to the above coding table, and output the corresponding characters. In this way, all data can be encoded continuously.
According to the above rules, the text Man is encoded as follows:

[root@centos8 ~]#echo -n Man | base64 #-n remove carriage return and add carriage return by default
[root@centos8 ~]#echo TWFu | base64 -d
Man[root@centos8 ~]#
[root@centos8 ~]#echo -n ab | base64
[root@centos8 ~]#echo -n ab | base64 | base64 -d
ab[root@centos8 ~]#

2.3 openssl command

Two modes of operation:

  • Interactive mode
  • Batch mode

Three sub orders:

  • Standard command
  • Message summary command
  • Encryption command
[root@centos8 ~]#openssl version viewing version
OpenSSL 1.1.1 FIPS  11 Sep 2018
[root@centos8 ~]#openssl help
Standard commands
asn1parse     ca        ciphers      cms       
crl        crl2pkcs7     dgst       dhparam     
dsa        dsaparam     ec        ecparam     
enc        engine      errstr      gendsa      
genpkey      genrsa      help       list       
nseq       ocsp       passwd      pkcs12      
pkcs7       pkcs8       pkey       pkeyparam
[root@centos8 ~]#openssl
OpenSSL> help
Standard commands
asn1parse     ca        ciphers      cms       
crl        crl2pkcs7     dgst       dhparam     
OpenSSL> ca --help
Usage: ca [options]
Valid options are:
-help          Display this summary
-verbose        Verbose output during processing
-config val       A config file
[root@centos8 ~]#

2.3.1 openssl command symmetric encryption

Tools: openssl enc, gpg
Algorithm: 3des, aes, blowfish, twofish
Enc command: help: man enc

openssl enc -e -des3 -a -salt -in testfile -out testfile.cipher
-e:  encryption
-a:  Use base64 Preservation
-des3 algorithm


openssl enc -d -des3 -a -salt –in testfile.cipher -out testfile
-d Decrypt

2.3.2 one way encryption of OpenSSL command (hash algorithm)

Tools: openssl dgst
Algorithm: md5sum, sha1sum, sha224sum,sha256sum

Dgst command: help: man dgst

openssl dgst -md5 [-hex default] /PATH/SOMEFILE
openssl dgst -md5 testfile
openssl dgst --md5 testfile
//Equivalent to md5sum testfile MD5 has been cracked suggestion -- sha512

Supplementary knowledge:
MAC: Message Authentication Code, an extended application of one-way encryption, is used to ensure the number of transmitted data in network communication
Integrity mechanism of evidence
HMAC: hash based MAC, using md5 or sha1 algorithm

2.3.3 generating user password with OpenSSL command

passwd command: help: man sslpasswd

openssl passwd -1 -salt SALT(Up to 8 bits.)
openssl passwd -1 –salt centos
-1: md5
-6: sha512

2.3.4 generating random numbers with OpenSSL command

Random number generator: pseudo-random number, using keyboard and mouse, block device interrupt to generate random number
/dev/random: return random number from entropy pool only; random number exhausted, blocking
/Dev / random: return random number from entropy pool; when the random number is exhausted, the software will generate pseudo-random number, non blocking
Help: man sslrand

openssl rand -base64|-hex NUM
NUM: Represents the number of bytes, using-hex,Each character is hexadecimal, equivalent to 4-bit binary, and the number of characters is NUM*2

Example: generate random 10 digit length password

[root@centos8 ~]#openssl rand -base64 9 |head -c10
# Nine bytes, one byte, eight bits, 8 * 9 = 72 bits can be divided by six, base code, six bits, so there is no equal sign
ip97t6qQes[root@centos8 ~]#
[root@centos8 ~]#tr -dc '[:alnum:]' < /dev/urandom |head -c10
DO2mDp3eZu[root@centos8 ~]#

2.3.5 openssl command to realize PKI (asymmetric key encryption)

Public key encryption:
Algorithm: RSA, ELGamal
Tools: gpg, openssl rsautl (man rsautl)
Digital signature:
Algorithm: RSA, DSA, ELGamal
Key exchange:
Algorithm: dh
DSA: Digital Signature Algorithm
DSS: Digital Signature Standard
openssl command generates key pair: man genrsa

Generate private key

(centos7 Do not set security 600 permissions)
openssl genrsa -out /PATH/TO/PRIVATEKEY.FILE 

Case study:

#Generate private key for symmetric key encryption
(umask 077; openssl genrsa –out test.key –des 2048)
The value of the opening sub shell umask in parentheses is 022
 Realize automation, generally with authority and no password
 #Encryption symmetric key
openssl genrsa -out test.key -des3 1024
 #Decrypt the encryption symmetric key
openssl rsa -in test.key –out test2.key

Extract public key from private key (cannot reverse)

openssl rsa -in PRIVATEKEYFILE –pubout –out PUBLICKEYFILE


openssl rsa –in test.key –pubout –out

Example centos7 creates a 600 permission private key directly:

[root@centos7 ~]#(umask 066;openssl genrsa -out /data/app.key)
Generating RSA private key, 2048 bit long modulus
e is 65537 (0x10001)
[root@centos7 ~]#ls -l /data/
total 4
-rw------- 1 root root 1679 Feb  3 15:26 app.key
[root@centos8 ~]#openssl genrsa -out /data/app.key 1024
Generating RSA private key, 1024 bit long modulus (2 primes)
e is 65537 (0x010001)
[root@centos8 ~]#ll /data/app.key
-rw------- 1 root root 891 Feb  3 14:52 /data/app.key


[root@centos8 ~]#openssl rsa -in /data/app.key -pubout -out /data/
writing RSA key
[root@centos8 ~]#ls -l /data/
total 8
-rw------- 1 root root 887 Feb  3 15:28 app.key
-rw-r--r-- 1 root root 272 Feb  3 15:32
[root@centos8 ~]#cat /data/
-----END PUBLIC KEY-----

Example: generate the encrypted private key and decrypt it

[root@centos8 ~]#openssl genrsa -out /data/app.key -des3 1024
Generating RSA private key, 1024 bit long modulus (2 primes)
e is 65537 (0x010001)
Enter pass phrase for /data/app.key:
Verifying - Enter pass phrase for /data/app.key:
[root@centos8 ~]#ls -l /data
total 4
-rw------- 1 root root 963 Feb  3 15:27 app.key
[root@centos8 ~]#cat /data/app.key
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,577C3B861BAD86B6
[root@centos8 ~]#openssl rsa -in /data/app.key -out /data/app.key
Enter pass phrase for /data/app.key:
writing RSA key
[root@centos8 ~]#ls -l /data
total 4
-rw------- 1 root root 887 Feb  3 15:28 app.key
[root@centos8 ~]#cat /data/app.key

2.4 establish private CA to realize certificate application issuance

To create a private CA:

  • OpenCA: a set of perfect PKI free software developed by OpenCA open source organization using Perl for OpenSSL
  • openssl

Certificate application and signing steps:
1. Generate request
2, RA verification
3, CA signed
4. Get certificate
Configuration file for openssl:


Three strategies: match matching, optional and supplied
match: the information filled in by the application must be consistent with the CA setting information
Optional: optional, inconsistent with CA setting information
supplied: this application information is required


[root@centos8 ~]#cat /etc/pki/tls/openssl.cnf
####################################################################Default CA information
[ ca ]
default_ca = CA_default # The default ca section
[ CA_default ]
dir = /etc/pki/CA # Where everything is kept default relevant data path does not exist by default centos7 installation default is
certs = $dir/certs # Where the issued certs are kept
crl_dir = $dir/crl # Where the issued crl are kept
database = $dir/index.txt # database index file. Issue certificate registration record issued certificate number, etc
#unique_subject = no # Set to 'no' to allow creation of
# several certs with same subject.
new_certs_dir = $dir/newcerts # default place for new certs
certificate = $dir/cacert.pem # The CA certificate CA's own certificate
serial = $dir/serial # The current serial number the next certificate number to be issued is automatically increased by 1 after it is issued. No setting is required by default
crlnumber = $dir/crlnumber # the current crl number
# must be commented out to leave a V1 CRL
crl = $dir/crl.pem # The current CRL certificate revocation file
private_key = $dir/private/cakey.pem# The file name of The private key CA private key file
RANDFILE = $dir/private/.rand # private random number file
x509_extensions = usr_cert # The extensions to add to the cert
# Comment out the following two lines for the "traditional"
# (and highly broken) format.
name_opt = ca_default # Subject Name options
cert_opt = ca_default # Certificate field options
default_days = 365 # How long to certificate for
default_crl_days= 30 # how long before next CRL certificate list is released once every 30 days
default_md = sha256 # use SHA-256 by default
preserve = no # keep passed DN ordering
policy = policy_match #Whether the key issuing certificate filling information matches what is the same and what is different
# For the CA policy
[ policy_match ] Default policy
countryName = match National agreement
stateOrProvinceName = match Regional consistency
organizationName = match Company unanimous
organizationalUnitName = optional department
commonName = supplied Common name website name
emailAddress = optional E-mail address
# For the 'anything' policy
# At this point in time, you must list all acceptable 'object'
# types.
[ policy_anything ]
countryName = optional #No consistency required
stateOrProvinceName = optional#No consistency required
localityName = optional#No consistency required
organizationName = optional#No consistency required
organizationalUnitName = optional#No consistency required

(important) 2.4.1 create private CA

1. Files needed to create CA

#Build certificate index database file
 touch /etc/pki/CA/index.txt does not have the directory and file by default
 #Specifies the serial number of the first issued certificate
 Echo 01 > / etc / PKI / Ca / serial does not have the directory and file by default

2. Generate CA private key

[09:45:53 root@27 pki]#cd /etc/pki/CA
[09:46:01 root@27 CA]#tree
├── certs
├── crl
├── newcerts
└── private 
#centos8 has no directory by default
4 directories, 0 files
(umask 066; openssl genrsa -out private/cakey.pem 2048)

3. Generate CA self signed certificate

OpenSSL req - New - x509 - key / etc / PKI / Ca / private / cakey.pem - Days 3650 - out / etc / PKI / Ca / cacert.pem self signed certificate must use this name

Option Description:

-New: generate new certificate signing request
 -x509: special for CA to generate self signed certificate
 -Key: the private key file used to generate the request
 -days n: validity period of certificate
 -out /PATH/TO/SOMECERTFILE: save path of certificate

Country code:
Example: generate self signed certificate

[root@centos8 ~]#openssl req -utf8 -newkey rsa:1024 -subj "/" -
keyout app.key -nodes -x509 -out app.crt
Generating a RSA private key
writing new private key to 'app.key'
[root@centos8 ~]#openssl x509 -in app.crt -noout -text
   Version: 3 (0x2)
   Serial Number:
   Signature Algorithm: sha256WithRSAEncryption
   Issuer: CN =
     Not Before: Feb  4 15:51:39 2020 GMT
   Not After : Mar  5 15:51:39 2020 GMT
   Subject: CN =
   Subject Public Key Info:
     Public Key Algorithm: rsaEncryption
       RSA Public-Key: (1024 bit)
       Exponent: 65537 (0x10001)
   X509v3 extensions:
     X509v3 Subject Key Identifier:
     X509v3 Authority Key Identifier:
     X509v3 Basic Constraints: critical
 Signature Algorithm: sha256WithRSAEncryption
[root@centos8 ~]#  

(important) 2.4.2 apply for and issue certificate

1. Generate the private key for the host that needs to use the certificate

(umask 066; openssl genrsa -out /data/test.key 2048)

2. Generate certificate request files for hosts that need to use certificates

openssl req -new -key /data/test.key -out /data/test.csr Must be csr Suffix

3. Sign certificate at CA and issue certificate to requester

openssl ca -in /data/test.csr -out /etc/pki/CA/certs/test.crt -days 30

Note: by default, country, province and company name must be consistent with CA

4. To view information in a certificate:

openssl x509 -in /PATH/FROM/CERT_FILE -noout  -text|issuer|subject|serial|dates
openssl x509 -in /data/mysql.cs  -noout  -serial -subject
//Select subject content to view
#View certificate status for the specified number
openssl ca -status SERIAL
cat /etc/pki/CA/index.txt In fact, view this file

5 copy certificate

unique_subject = yes requires content uniqueness modifiable no
 Reissue to use
cp app.key mysql.key
cp app.csr mysql.csr
 Reissue to use
 openssl ca -in /data/mysql.csr -out /etc/pki/CA/certs/mysql.crt -days 100 default 365 days
 Same content certificate number changed

(understanding) 2.4.3 revocation of certificate

Get the serial of the certificate to revoke on the client

openssl x509 -in /PATH/FROM/CERT_FILE  -noout  -serial -subject

On the CA, according to the serial and subject information submitted by the customer, check whether it is consistent with the information in the index.txt file, and revoke the certificate:

openssl ca -revoke /etc/pki/CA/newcerts/SERIAL.pem
openssl ca -revoke /etc/pki/CA/newcerts/11.pem
openssl ca -revoke /etc/pki/CA/certs/docker.crt

Specify the number of the first revocation certificate. Note: you need to execute the

echo 01 > /etc/pki/CA/crlnumber

Update certificate revocation list

openssl ca -gencrl -out /etc/pki/CA/crl.pem

To view a revocation crl file:

openssl crl -in /etc/pki/CA/crl.pem -noout -text
Revocation example:
[11:57:39 root@27 data]#cat /etc/pki/CA/index.txt
V	201204035739Z		01	unknown	/C=CN/ST=hebei/O=magedu/OU=it/
[11:58:28 root@27 data]#openssl ca -revoke /etc/pki/CA/newcerts/01.pem
Using configuration from /etc/pki/tls/openssl.cnf
Revoking Certificate 01.
Data Base Updated
[11:59:46 root@27 data]#cat /etc/pki/CA/index.txt
R(Indicates it has been revoked)	201204035739Z	200208035946Z	01	unknown	/C=CN/ST=hebei/O=magedu/OU=it/
[11:59:49 root@27 data]#openssl ca -gencrl -out /etc/pki/CA/crl.pem
//Or openssl ca -gencrl -out /etc/pki/CA/crl.pem
Using configuration from /etc/pki/tls/openssl.cnf #Error updating revocation list no / etc/pki/CA/crlnumber revocation file needs to be assigned
[12:01:45 root@27 data]#openssl crl -in /etc/pki/CA/crl.pem -noout -text to view the revocation file, which can be transferred to windows to view and need to be modified to CRL suffix
Certificate Revocation List (CRL):
        Version 2 (0x1)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: /C=CN/ST=hebei/L=zhangjiakou/O=magedu/OU=it/
        Last Update: Feb  8 04:01:37 2020 GMT
        Next Update: Mar  9 04:01:37 2020 GMT
        CRL extensions:
            X509v3 CRL Number: 
Revoked Certificates:
    Serial Number: 01
        Revocation Date: Feb  8 03:59:46 2020 GMT
    Signature Algorithm: sha256WithRSAEncryption

centos7 create self signed certificate

[root@centos7 ~]#cd /etc/pki/tls/certs
[root@centos7 certs]#make view usage
This makefile allows you to create:
o public/private key pairs
o SSL certificate signing requests (CSRs)
o self-signed SSL test certificates
To create a key pair, run "make SOMETHING.key".
To create a CSR, run "make SOMETHING.csr".
To create a test certificate, run "make SOMETHING.crt".
To create a key and a test certificate in one file, run "make SOMETHING.pem".
To create a key for use with Apache, run "make genkey".
To create a CSR for use with Apache, run "make certreq".
To create a test certificate for use with Apache, run "make testcert".
To create a test certificate with serial number other than random, add
You can also specify key length with KEYLEN=n and expiration in days with DAYS=n
Any additional options can be passed to openssl req via EXTRA_FLAGS
 make server.key
 make server.csr
 make server.crt
 make stunnel.pem
 make genkey
 make certreq
 make testcert
 make server.crt SERIAL=1
 make stunnel.pem EXTRA_FLAGS=-sha384
 make testcert DAYS=600
[root@centos7 certs]#ls
ca-bundle.crt make-dummy-cert Makefile(Executive documents) renew-dummy-cert
[root@centos7 certs]#cat Makefile
UTF8 := $(shell locale -c LC_CTYPE -k | grep -q charmap.*UTF-8 && echo -utf8)
ifdef SERIAL
EXTRA_FLAGS+=-set_serial $(SERIAL)
.PHONY: usage
.SUFFIXES: .key .csr .crt .pem
.PRECIOUS: %.key %.csr %.crt %.pem
@echo "This makefile allows you to create:"
@echo " o public/private key pairs"
@echo " o SSL certificate signing requests (CSRs)"
@echo " o self-signed SSL test certificates"
@echo "To create a key pair, run \"make SOMETHING.key\"."
@echo "To create a CSR, run \"make SOMETHING.csr\"."
@echo "To create a test certificate, run \"make SOMETHING.crt\"."
@echo "To create a key and a test certificate in one file, run \"make
@echo "To create a key for use with Apache, run \"make genkey\"."
@echo "To create a CSR for use with Apache, run \"make certreq\"."
@echo "To create a test certificate for use with Apache, run \"make
@echo "To create a test certificate with serial number other than random,
add SERIAL=num"
@echo "You can also specify key length with KEYLEN=n and expiration in days
with DAYS=n"
@echo "Any additional options can be passed to openssl req via EXTRA_FLAGS"
@echo Examples:
@echo " make server.key"
@echo " make server.csr"
@echo " make server.crt"
@echo " make stunnel.pem"
@echo " make genkey"
@echo " make certreq"
@echo " make testcert"
@echo " make server.crt SERIAL=1"
@echo " make stunnel.pem EXTRA_FLAGS=-sha384"
@echo " make testcert DAYS=600"
umask 77 ; \
PEM1=`/bin/mktemp /tmp/openssl.XXXXXX` ; \ #Generate random file
PEM2=`/bin/mktemp /tmp/openssl.XXXXXX` ; \
/usr/bin/openssl req $(UTF8) -newkey $(TYPE) -keyout $$PEM1 -nodes -x509 -
days $(DAYS) -out $$PEM2 $(EXTRA_FLAGS) ; \
cat $$PEM1 >  $@ ; \
echo ""  >> $@ ; \
cat $$PEM2 >> $@ ; \
$(RM) $$PEM1 $$PEM2
umask 77 ; \
/usr/bin/openssl genrsa -aes128 $(KEYLEN) > $@
%.csr: %.key
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $^ -out $@
%.crt: %.key
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $^ -x509 -days $(DAYS) -out $@
genkey: $(KEY)
certreq: $(CSR)
testcert: $(CRT)
$(CSR): $(KEY)
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $(KEY) -out $(CSR)
$(CRT): $(KEY)
umask 77 ; \
/usr/bin/openssl req $(UTF8) -new -key $(KEY) -x509 -days $(DAYS) -out
[root@centos7 certs]#
[root@centos7 certs]#make app.crt
umask 77 ; \
/usr/bin/openssl genrsa -aes128 2048 > app.key
Generating RSA private key, 2048 bit long modulus
e is 65537 (0x10001)
Enter pass phrase:
Verifying - Enter pass phrase:
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key app.key -x509 -days 365 -out app.crt
Enter pass phrase for app.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,

If you enter '.', the field will be left blank.

Country Name (2 letter code) [XX]:CN #Import countries in turn
State or Province Name (full name) []:hubei #Province
Locality Name (eg, city) [Default City]:wuhan#City
Organization Name (eg, company) [Default Company Ltd]:magedu #company
Organizational Unit Name (eg, section) []:it
Common Name (eg, your name or your server's hostname) [] #To whom?
Email Address [] #mailbox
[root@centos7 certs]#ls
app.crt app.key ca-bundle.crt make-dummy-cert Makefile
[root@centos7 certs]#openssl x509 -in app.crt -noout -text view information
   Version: 3 (0x2)
   Serial Number:
 Signature Algorithm: sha256WithRSAEncryption
   Issuer: C=CN, ST=hubei, L=wuhan, O=magedu, OU=it,
     Not Before: Feb  5 00:28:31 2020 GMT
     Not After : Feb  4 00:28:31 2021 GMT
   Subject: C=CN, ST=hubei, L=wuhan, O=magedu, OU=it,
   Subject Public Key Info:
     Public Key Algorithm: rsaEncryption
       Public-Key: (2048 bit)
       Exponent: 65537 (0x10001)
   X509v3 extensions:
     X509v3 Subject Key Identifier:
     X509v3 Authority Key Identifier:

​     X509v3 Basic Constraints:
​       CA:TRUE
 Signature Algorithm: sha256WithRSAEncryption
​    a3:66:1b:85:dc:9e:1b:c7:c8:e4:29:3c:32:b2:fc:71:c9:79:
​    9e:ad:db:78:bd:a4:42:1a:ef:d7:7f:4a:84:d9:46:e1:60:fa:
​   ...Process ellipsis
[root@27 certs]# cat app.key 
Proc-Type: 4,ENCRYPTED Show encrypted key
DEK-Info: AES-128-CBC,9DA9313678745075B8A73ADCF93A7B32

...Process ellipsis
[root@27 certs]# openssl rsa -in app.key -out app.key #Decrypt
Enter pass phrase for app.key:
writing RSA key
[root@27 certs]# cat app.key 
-----BEGIN RSA PRIVATE KEY-----#Decrypt
...Content ellipsis
[root@27 certs]# Cat app.crt app.key > app.pem redirect to. PEM
[root@27 certs]# Some software of cat app.pem requires that the certificate and private key should be placed in one file. PEM format can also be used to directly generate PEM file make app.pem
-----BEGIN CERTIFICATE----- #certificate
...Process ellipsis
-----BEGIN RSA PRIVATE KEY-----# key
...Process ellipsis
[root@27 certs]# 

centos8 does not have this file to send to the target host

scp /etc/pki/tls/certs/Makefile
Published 6 original articles, won praise 0, visited 237
Private letter follow

Tags: OpenSSL Apache Makefile SSL

Posted on Mon, 10 Feb 2020 04:33:27 -0800 by Thoughtless