openssl usage

最後更新: 2023-08-01

名詞

  • csr: certificate signing request
  • crt: certificate

 

目錄

 


建立 Private Key

 

Syntax

openssl genrsa [-out filename] [numbits]

Example:

openssl genrsa -out server.key 2048

# 加密 Private Key

openssl genrsa -des3 -out server.key 2048

  • -des3        encrypt the private key with des3

Verify Key

openssl rsa -in server.key -noout -check

RSA key ok

 


Decrypt Private Key

 

有加密的 Key File

-----BEGIN ENCRYPTED PRIVATE KEY-----
...
-----END ENCRYPTED PRIVATE KEY-----

沒有加密的 key file

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

# 安全起見勿用 ">" 改用 ">>"

openssl rsa -in MYKEY.key >> MYKEY-NOCRYPT.key

 


建立 csr

 

由 key 建立 csr

openssl req -out MYCSR.csr -key MYKEY.key -new

同時建立 key 及 csr

openssl req -out MYCSR.csr -pubkey -new -keyout MYKEY.key

  • Add "-nodes" to create an unencrypted private key
  • Add "-config" <openssl.cnf> if your config file has not been set in the environment

由 crt 建立 csr

openssl x509 -x509toreq -in MYCRT.crt -out MYCSR.csr -signkey MYKEY.key

Setting

openssl.cnf:

...............................

[ CA_default ]

dir             = $ENV::KEY_DIR         # Where everything is kept
certs           = $dir                  # Where the issued certs are kept
crl_dir         = $dir                  # Where the issued crl are kept
database        = $dir/index.txt        # database index file.
new_certs_dir   = $dir                  # default place for new certs.

certificate     = $dir/ca.crt           # The CA certificate
serial          = $dir/serial           # The current serial number
crl             = $dir/crl.pem          # The current CRL
private_key     = $dir/ca.key           # The private key
RANDFILE        = $dir/.rand            # private random number file

...............................

 


openssl check private public key match

 

crt & key & csr info.

openssl x509 -noout -text -in server.crt

openssl rsa -noout -text -in server.key

 openssl req -noout -text -in server.csr

Remark

openssl x509 -noout -subject -in server.crt

crt, key, csr 是否一對

The "Modulus" and the "Exponent" portions in the key and the Certificate must match.

...
Subject Public Key Info:
    Public Key Algorithm: rsaEncryption
        Public-Key: (1024 bit)
        Modulus:
            00:c1:4c:95:30:09:e7:2a:09:a2:6a:38:23:49:da:
            ....
        Exponent: 65537 (0x10001)
...

Checking

openssl x509 -noout -modulus -in server.crt | openssl md5

openssl rsa -noout -modulus -in server.key | openssl md5

openssl req -noout -modulus -in server.csr | openssl md5

 


建立 Self-signed certificate (CA)

 

# 如果 key 已準備好:

openssl req -new -x509 -days 3650 -key ca.key -out ca.crt

OR

# 同時建立 key 及 crt

openssl req -new -x509 -days 3650 -keyout ca.key -out ca.crt [-newkey rsa:2048]

Useful Opts:

-config openssl.cnf

Certificate no password:

UI_set_result:result too small

openssl req -new -x509 -days 3650 -nodes -keyout server.key -out server.cert

Auto Answer

DOMAIN=server

SUBJ="/C=CN/ST=HONG KONG/L=HK/O=Company Name/OU=Information Technology/CN=${DOMAIN}/emailAddress=postmaster@${DOMAIN}"

openssl req ... -subj "$SUBJ"

Sign a Certificate Signing Request

openssl x509 -req -in MYCSR.csr -CA MY-CA-CERT.crt -CAkey MY-CA-KEY.key -CAcreateserial -out MYCERT.crt -days 365

Opt:

-CAcreateserial           # create serial number file if it does not exist

Multiple Domains

Common Name (eg, your name or your server's hostname) []: *.datahunter.org

 


Checking

 

Check a private key

openssl rsa -in privateKey.key -check

Enter pass phrase for ca.key:

RSA key ok
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
..........
-----END RSA PRIVATE KEY-----

Check a certificate (info)

openssl x509 -in certificate.crt -text -noout

-noout 會沒有以下一段

-----BEGIN CERTIFICATE-----
..............

-----END CERTIFICATE-----

Example Output:

Certificate:
    Data:
        Version: 1 (0x0)
        Serial Number:
            b3:5f:14:ee:53:cb:0e:79
        Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=CN, ST=HK, L=HK, O=Test, OU=test
        Validity
            Not Before: Sep 20 10:19:01 2012 GMT
            Not After : Oct 20 10:19:01 2012 GMT
        Subject: C=CN, ST=China, L=HK, O=COMPANY, OU=COMPANY, CN=www.DOMAIN/emailAddress=webmaster@DOMAIN
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (2048 bit)
                Modulus (2048 bit):
...................

Check a Certificate Signing Request (CSR)

openssl req -in mycsr.csr -noout -text

Certificate Request:
    Data:
        Version: 0 (0x0)
        Subject: C=CN, ST=China, L=HK, O=COMPANY, OU=COMPANY, CN=www.DOMAIN/emailAddress=webmaster@DOMAIN
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
            RSA Public Key: (2048 bit)
                Modulus (2048 bit):

Check a Certificate

openssl verify mycert.pem

Verify Certificate matches the Private key

# 方法: compare the Modulus

The server certificate, private key and CSR all contain a Modulus value.  

This value must match, otherwise there will be an error.

# To view the modulus

openssl rsa -noout -modulus -in FILE.key | openssl md5

openssl req -noout -modulus -in FILE.csr  | openssl md5

openssl x509 -noout -modulus -in FILE.crt  | openssl md5

Server/Client Connection Checking

server: start https server with key & pem

openssl s_server -accept 8443 -key ./private/mykey.key -cert ./certs/mycrt.pem -www

client: https client ( man s_client )

https: HTTP over SSL, 加 "| tee logfile" 可以 log 到張 Cert.

openssl s_client -connect localhost:8443

s_client with other protocol test(smtp/pop3/imap..):

openssl s_client -connect ${REMHOST}:${REMPORT}

Example:

# port 25/TLS; use same syntax for port 587

    openssl s_client -connect REMHOST:25 -starttls smtp

    * -starttls protocol        # "smtp", "pop3", "imap", and "ftp"

    * TLS 選項: -tls1, -tls1_1, -tls1_2

# SSL - 465/tcp

    openssl s_client -connect remote.host:465 -crlf

    鍵入 "Enter" 會變成 "CR+LF"

# imaps: IMAP over SSL

    openssl s_client -connect remote.host:993

    Notes: 連 Office 365 要用 "-crlf"

    openssl s_client -connect outlook.office365.com:993 -crlf

# pop3s: POP-3 over SSL

    openssl s_client -connect remote.host:995

showcerts

# -showcerts if you want to download all the certificates in the chain.

openssl s_client -showcerts -connect localhost:465

echo quit | openssl s_client -showcerts -servername file.datahunter.org -connect datahunter.org:443 > cacert.pem

  • -servername name    # Set the TLS SNI (Server Name Indication) extension in the ClientHello message.
depth=2 O = Digital Signature Trust Co., CN = DST Root CA X3
verify return:1
depth=1 C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
verify return:1
depth=0 CN = datahunter.org
verify return:1
DONE

Useful Opt

-quiet

Inhibit printing of session and certificate information.

This implicitly turns on -ign_eof as well.

-no_ign_eof

Shut down the connection when end of file is reached in the input.

Can be used to override the implicit -ign_eof after -quiet.

i.e.

openssl s_client -quiet -no_ign_eof -connect datahunter.org:21 -starttls ftp </dev/null

gnutls-cli  - GNU TLS test client <== 它 Display 得更清楚 (subject, expires, fingerprint)

-s, --starttls

-p, --port integer     # Default: 443

--print-cert              # Print the certificate in PEM format.

Usage:

  gnutls-cli --print-cert www.example.com < /dev/null > www.example.com.certs

  相當於

  echo -n | openssl s_client -connect HOST:PORTNUMBER | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert

 


Gen DH File

 

New Version

openssl dhparam 2048 > dh2048.pem

Old Version

openssl gendh 2048 > dh2048.pem

 


CRL

 

info:

openssl crl -text -noout -in crl.pem

建立:

Step1: 建立一個空的 crl.pem

openssl ca -keyfile ca.key -cert ca.crt  -gencrl -out crl.pem \
-config /usr/share/easy-rsa/2.0/openssl-1.0.0.cnf

Certificate Revocation List (CRL):
        Version 1 (0x0)
    Signature Algorithm: md5WithRSAEncryption
        Issuer: /C=CN/ST=HK/L=Hong Kong/O=???/OU=IT/CN=changeme/name=changeme/emailAddress=???@???
        Last Update: Jan  3 08:28:19 2014 GMT
        Next Update: Feb  2 08:28:19 2014 GMT
No Revoked Certificates.
    Signature Algorithm: md5WithRSAEncryption
         c0:56:43:75:a3:78:77:5f:92:4d:f8:92:62:8f:ed:5b:16:a5:
         c8:72:03:cd:7e:02:15:d4:7e:c9:b1:2a:a5:74:6a:ef:5a:3c:
         00:90:74:b1:03:fe:b0:f2:ac:0b:af:81:06:ee:63:0b:bf:ab:

Step2: 建立一個 UserA 的 CRL

建立一個 UserA 的 CRL

openssl ca -keyfile ca.key -cert ca.crt -revoke UserA.crt \
-config /usr/share/easy-rsa/2.0/openssl-1.0.0.cnf

它會修改 index.txt

R       240101081356Z   140103084330Z   03      unknown /C=CN/ST=HK/L=Hong Ko ............

Step3: 更新 crl.pem

openssl ca -keyfile ca.key -cert ca.crt -gencrl -out crl.pem  \
-config /usr/share/easy-rsa/2.0/openssl-1.0.0.cnf

 


Other Usage

 

prime (test 13)

openssl prime 13

D is prime

rand (8byte)

openssl rand 8

passwd (MD5 PW with salt)

openssl passwd -1 -salt 234 MySecret

speed(Benchmarking)

openssl speed rsa

                  sign    verify    sign/s verify/s
rsa  512 bits 0.000156s 0.000014s   6424.1  73804.7
rsa 1024 bits 0.000832s 0.000052s   1201.4  19294.7
rsa 2048 bits 0.006534s 0.000177s    153.0   5656.8
rsa 4096 bits 0.043377s 0.000674s     23.1   1484.2

# with "-evp", you benefit from the automatic selection of the improved implementation, based on the current CPU model,

# on "aes", it detects whether the current CPU supports the AES-NI instructions,

openssl speed -evp aes-256-gcm

Doing aes-256-gcm for 3s on 16 size blocks: 14013886 aes-256-gcm's in 2.21s
Doing aes-256-gcm for 3s on 64 size blocks: 8394412 aes-256-gcm's in 1.84s
Doing aes-256-gcm for 3s on 256 size blocks: 3894544 aes-256-gcm's in 2.01s
Doing aes-256-gcm for 3s on 1024 size blocks: 877851 aes-256-gcm's in 1.45s
Doing aes-256-gcm for 3s on 8192 size blocks: 148651 aes-256-gcm's in 1.91s
...
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
aes-256-gcm     101458.00k   291979.55k   496021.52k   619944.43k   637564.92k

說明

run the aes-256-gcm routine in a loop for 3 seconds with a 16 byte input.

After 2.21 seconds, we ran just a bit over 14 million iterations.

有硬解與沒硬解比較

lscpu | grep aes

evp 有 aes-256-gcm, 但沒有 evp 時只有 aes-256-cbc, 所以我們用 aes-256-cbc 去比較

openssl speed aes-256-cbc

Doing aes-256 cbc for 3s on 16 size blocks: 2477937 aes-256 cbc's in 1.38s
Doing aes-256 cbc for 3s on 64 size blocks: 807925 aes-256 cbc's in 1.77s
...

openssl speed -evp aes-256-cbc

Doing aes-256-cbc for 3s on 16 size blocks: 24644729 aes-256-cbc's in 2.03s
Doing aes-256-cbc for 3s on 64 size blocks: 6070838 aes-256-cbc's in 1.96s
...

Available options:

  • -engine e      # use engine e, possibly a hardware device.
  • -evp e          # use EVP e.
  • -decrypt       # time decryption instead of encryption (only EVP).
  • -mr              # produce machine readable output.
  • -multi n        # run n benchmarks in parallel.

hash

openssl speed sha1

Doing sha1 for 3s on 16 size blocks: 12402266 sha1's in 3.00s
Doing sha1 for 3s on 64 size blocks: 8851013 sha1's in 2.99s
Doing sha1 for 3s on 256 size blocks: 4911363 sha1's in 3.00s
Doing sha1 for 3s on 1024 size blocks: 1769888 sha1's in 3.00s
Doing sha1 for 3s on 8192 size blocks: 252989 sha1's in 3.00s
...
The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
sha1             66424.02k   189480.04k   419951.02k   605996.35k   691104.43k

 

dgst (man dgst)

openssl dgst -md5 sendmail.py

MD5(sendmail.py)= 3ff007d3e9a46d2e19db5e8be099e698

 


pkcs12

 

# Check a PKCS#12 file

openssl pkcs12 -info -in keyStore.p12

入完第一次 password ("Enter Import Password:")

會顯示 Certificate (Server, CA)

再入一次 password (Enter PEM pass phrase: Verifying - Enter PEM pass phrase:)

會顯示加密了的 private key , 並再以 pem 格式輸出.

# Convert pfx to pem (pkcs12)

# Private key & Certificate pair combined into a single file

# -nodes                    don't encrypt the private keys

# -in filename             PKCS#12 file to be parsed

openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes

# 只 export Certificate (-nokeys)

openssl pkcs12 -in file.pfx -out cert.nokey.pem -nokeys

# 只 export Private key (-nocerts)

openssl pkcs12 -in file.pfx -out priv.key.pem -nocerts -nodes

 

# Convert pem to pfx

Binary format that contains the certificate with a corresponding private key and is protected by a password

The file can include the CA chain certificates as well

PFX certificates are used on Windows machines

openssl pkcs12 -export -out your_pfx_certificate.pfx -inkey your_private.key -in your_pem_certificate.crt -certfile CA-bundle.crt

 

# Create a PKCS#12 file

# -name friendlyname    # displayed in list boxes by software

# -export                      # This option specifies that a PKCS#12 file will be created rather than parsed.

openssl pkcs12 -export -nodes -name "192.168.88.14" -in certificate.crt -inkey privateKey.key -out mycert.pfx

 


Get fingerprint from crt file

 

From crt file:

# Get SHA-1 fingerprint

openssl x509 -noout -fingerprint -in server.crt

SHA1 Fingerprint=D5:5B:DD:2C:F7:66:1E:4E:E9:2B:52:D0:64:D3:CE:50:89:94:10:25

# Get SHA-256 fingerprint

openssl x509 -noout -fingerprint -sha256 -in server.crt

From network:

(SSL) Tells curl to use the specified certificate file to verify the peer.

openssl s_client -servername server.com -connect server.com:443 | openssl x509 -fingerprint -noout

 


Certificate Transparency(CT)

 

* open source framework for monitoring and auditing digital certificates

Certificate Transparency makes it possible to detect SSL certificates that have been mistakenly issued by a certificate authority or maliciously acquired from an otherwise unimpeachable certificate authority. It also makes it possible to identify certificate authorities that have gone rogue and are maliciously issuing certificates.

Chrome

http://www.certificate-transparency.org/

 

 


pfx (Personal Information Exchange)

 

P7B -> PEM

openssl pkcs7 -print_certs -in certificate.cer -out certificate.pem

certificate.cer

-----BEGIN PKCS7-----
.....................

-print_certs
           prints out any certificates or CRLs contained in the file.

Help:

man pkcs7

pem -> pfx

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

 


CA.cnf 的設定

 

# md stands for message digest and from openssl version 1.1 the default digest is sha256

default_md = sha256

# Don't add the email into cert DN

email_in_dn    = no

# default policy

policy         = policy_any

# serial no file

serial         = $dir/serial         

# how long to certify for

default_days   = 3650

Example: CA.cnf

dir            = /opt/burp/etc/CA

database       = $dir/index.txt
serial         = $dir/serial.txt
new_certs_dir  = $dir/newcerts
default_md     = sha256
email_in_dn    = no
policy         = policy_any
default_days   = 3650


[ policy_any ]
countryName            = optional
stateOrProvinceName    = optional
organizationName       = optional
organizationalUnitName = optional
commonName             = supplied
emailAddress           = optional

 


.cnf Configure File

 

request.cnf

[ req ]
default_bits           = 2048
countryName            = CN
stateOrProvinceName    = HK
localityName           = Hong Kong
0.organizationName     = Office
organizationalUnitName = Backup
emailAddress           = [email protected]
distinguished_name     = req_distinguished_name


[ req_distinguished_name ]

commonName                     = Common Name (eg, YOUR name)
commonName_max                 = 64

** unable to find 'distinguished_name' in config

distinguished_name

This specifies the section containing the distinguished name fields to prompt for when generating a certificate or certificate request.

DOC:

http://stuff.mit.edu/afs/athena/contrib/crypto/openssl.cnf

burp example

openssl req -config request.cnf -out winxp1.csr -key winxp1.key -new

openssl x509 -req -CAcreateserial -in winxp1.csr -CA /etc/burp/CA/CA_burpCA.crt -CAkey /etc/burp/CA/CA_burpCA.key -out winxp1.crt -days 3650

 


Supported Ciphers

 

# Display all SSL cipher

openssl ciphers

# Display cipher with RC4

openssl ciphers RC4

Keywords

  • eNULL, NULL    # The "NULL" ciphers that is those offering no encryption.
  • aNULL             # The cipher suites offering no authentication.
  • HIGH
  • MEDIUM
  • LOW
  • SSLv3
  • TLSv1
  • TLSv1.2

Examples

# -s    Only list system supported ciphers

openssl ciphers -s -v 'NULL'

 

# Verbose listing of all OpenSSL ciphers including NULL ciphers:

openssl ciphers -v 'ALL:NULL'

...
NULL-SHA256             TLSv1.2 Kx=RSA    Au=RSA  Enc=None      Mac=SHA256
NULL-SHA                SSLv3 Kx=RSA      Au=RSA  Enc=None      Mac=SHA1
NULL-MD5                SSLv3 Kx=RSA      Au=RSA  Enc=None      Mac=MD5

 


Certificate file (PEM format)

 

PEM format ( Privacy Enhanced Mail (RFC 1421 - RFC 1424) )

The PEM format often is used for representing a certificate, certificate request, PKCS#7 object,... in US-ASCII by base64 encoding it and putting the encoding

* a certificate chain can be included. The order is significant. (How to combine various certificates into single .pem)

order:

    Private key (放在尾都可以)
    Public certificate
    Intermidiate Certificate
    Root certificate

-----BEGIN CERTIFICATE-----
block of base64 encoded data
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
block of base64 encoded data
-----END RSA PRIVATE KEY-----

 

 


Binary Key&Cert to Pem Format

 

crt to pem

openssl x509 -inform der -in certificate.cer -out certificate.pem

key to pem

openssl rsa -inform der -in key.bin -outform pem -out key.pem

 


OpenSSL for Windows

 

DL

https://kb.firedaemon.com/support/solutions/articles/4000121705

Pre-compiled Win32/x64 1.1.1 libraries with dependency on the Visual Studio 2019 runtime (binary-compatible with 2015+2017).

Primarily built for FireDaemon Fusion, but may be used for any Windows application.

 


.well-known

 

中央化 SSL 申的 Verify 的 File Path

Centos 7

/etc/httpd/conf.d/pki-validation.conf

Alias /.well-known/pki-validation /var/www/html/.well-known/pki-validation

mkdir /var/www/html/.well-known/pki-validation -p

 


More Info.

 

Linux Update CA Certificates

 

 

 

Creative Commons license icon Creative Commons license icon