openssl - ghdrako/doc_snipets GitHub Wiki
-
https://www.openssl.org/docs/man3.0/man7/migration_guide.html
-
zmina niskopoziomego api na wysokopoziomowy
-
providers
-
curl
OpenSSL is an open source software toolkit that includes a cryptography and SSL/TLS library, as well as command-line utilities that use the library to provide some useful functionality on the command line, such as generating encryption keys and X.509 certificates. The main part of OpenSSL is its library, which means that OpenSSL is mainly useful for software developers.
OpenSSL supports a lot of cryptographic algorithms, among which are algorithms for symmetric and asymmetric encryption, digital signatures, essage digests, and key exchange. OpenSSL supports X.509 certificates, SSL, TLS, and DTLS protocols, as well as other cryptography-related technologies that are less popular.
The OpenSSL project used its BSD-style open source license until version 3.0. Since version 3.0, it uses Apache License 2.0.
The concept of OpenSSL operation implementation providers was introduced. A provider is a unit of code that provides the implementation of cryptographic algorithms. The existing OpenSSL cryptography code will mostly be available via Default and Legacy providers. Engines are still supported in OpenSSL 3.0 but have been deprecated in favor of providers.
When using KTLS, an application can create a special TLS socket, similar to a TCP socket. OpenSSL then performs a TLS handshake and hands the negotiated encryption key and other data to the operating system kernel in the form of TLS socket options. Then, the actual data transmission in the TLS protocol is handled by the KTLS code. Such TLS offloading to the kernel can speed up data transmission on high-load systems where performance is important, especially when the kernel can use hardware acceleration for Advanced Encryption Standard (AES) and thus offload the main CPU. Of course, KTLS support is needed both in the TLS library and in the operating system kernel. At the time of writing, only the Linux and FreeBSD kernels support KTLS.
Install OpenSSL on Debian or Ubuntu Linux, you only need to issue one command:
$ sudo apt install openssl libssl3 libssl-dev libssl-doc
man openssl-genpkey
OpenSSL has a concept of a Public or Private Key (PKEY). Very often when mentioning a private key, the documentation really means a keypair. It applies to both command-line tools documentation and OpenSSL API documentation.
ssh-keygen -t rsa -b 4096
openssl genrsa -out KEY1.pem 2048 # KeysGenerate 2048 bit RSA Private Key saved as KEY1.pem
openssl genrsa -out KEY2.pem -aes128 4096 # Generate 4096 bit RSA Private Key, encrypted with AES128
# safer to transfer between devices
It has been deprecated since OpenSSL 3.0, together with openssl genrsa, openssl rsautl, and other key type-specific subcommands.
$ openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:4096 \
-out rsa_keypair.pem
$ cat rsa_keypair.pem
-----BEGIN PRIVATE KEY-----
MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDC2/
sxiM72yGgy
... a lot of base64-encoded data …
FZTCpfZK4ecBXkHHaVnHBmdS10EyngU=
-----END PRIVATE KEY-----
The keypair is saved in the Privacy Enhanced Mail (PEM) format. PEM is the default format used by OpenSSL for storing keys or certificates. PEM format is really a Base64 wrapping around some binary data, with a text header (the BEGIN line) and a text footer (the END line). If you remove the header and the footer from the keypair PEM file and Base64-decode it, you will get the keypair in the Distinguished Encoding Rules (DER) format. DER is another popular format for storing keys and certificates supported by OpenSSL.
Extract the public key from the keypair:
$ openssl pkey \
-in rsa_keypair.pem \
-pubout \
-out rsa_public_key.pem
Inspect the structure of public key file
$ openssl pkey -pubin -in rsa_public_key.pem -noout -text
man openssl-pkey
- Key size must be last argument of command
- Omit -out argument to output to StdOut
- Other encryption algorithms are also supported:
-aes128, -aes192, -aes256, -des3, -des
-des
is unsecure not use !!! -des3
is use most of the time
openssl list -cipher-algorithms # list supported algorithms
BEGIN RSA PRIVATE KEY
is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY
is PKCS#8 and indicates that the key type is included in the key data itself. From the link:
- https://stackoverflow.com/questions/20065304/differences-between-begin-rsa-private-key-and-begin-private-key
- https://stackoverflow.com/questions/17733536/how-to-convert-a-private-key-to-an-rsa-private-key
To Convert BEGIN OPENSSH PRIVATE KEY
to BEGIN RSA PRIVATE KEY
(make a backup key first because replace !!!):
ssh-keygen -p -m PEM -f ~/.ssh/id_rsa
openssl dsaparam -out DSA-PARAM.pem 1024 # Generate DSA Parameters File
openssl gendsa -out DSA-KEY.pem DSA-PARAM.pem # Generate DSA Keys file with Parameters file
openssl dsaparam -genkey -out DSA-PARAM-KEY.pem 2048 # Generate DSA Parameters and Keys in one File
See Inspecting section to view file contents.
ssh-keygen -t ecdsa-b 512 -m PEM
openssl genpkey -genparam -algorithm EC -pkeyopt ec_paramgen_curve:secp384r1 -out EC-PARAM.pem # Generate EC Parameters file
openssl genpkey -paramfile EC-PARAM.pem -out EC-KEY.pem # Generate EC Keys from Parameters file
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-384 -out EC-KEY.pem # Generate EC Keys directly
openssl ecparam -list_curves # View supported Elliptic Curves
Recommended Curves: prime256v1, secp384r1, secp521r1
openssl x509 -in acs.cdroutertest.com.pem -text
openssl x509 -in MYCERT.der -inform der -text
openssl rsa -in KEY.pem -noout -text # Converting an RSA Private Key into text
openssl rsa -in ENCRYPTED-KEY.pem -out KEY.pem # Removing encryption from an RSA key file
openssl rsa -in KEY.pem -aes128 -out ENCRYPTED-KEY.pem # Encrypting an RSA Key File
man openssl-pkey
$ openssl pkey -in rsa_keypair.pem -noout -text # inspect the keypair structure
openssl dsaparam -in DSA-PARAM.pem -text -noout # Inspecting DSA Parameters file
openssl dsa -in DSA-KEY.pem -text -noout # Inspecting DSA Private Key file
openssl ecparam -in EC-PARAM.pem -text -noout # Inspecting Elliptic Curve (EC) Parameters file
openssl ec -in EC-KEY.pem -text -noout # Inspecting Elliptic Curve (EC) Private Key file
openssl pkey -in KEY.pem -noout -text # Converting any Private Key file into text (RSA, DSA, or EC)
openssl pkey -in KEY.pem -noout -text_pub # Extracting only Public Key as text from any Key file
openssl pkey -in KEY.pem -pubout # Extracting only Public Key in PEM format
pkey
expects a Private Key file. Public Key file can be read with -pubin
Compare Modulus values to see if files match each other
openssl req -in CSR.pem -noout -modulus
openssl x509 -in CERT.pem -noout -modulus
openssl rsa -in KEY.pem -noout -modulus
Compare Public Key values to see if files match each other
openssl req -in EC-CSR.pem -noout -pubkey
openssl x509 -in EC-CERT.pem -noout -pubkey
openssl ec -in EC-KEY.pem -pubout
openssl req -new -key KEY.pem -out CSR.pem # Generate CSR with existing Private Key file
openssl req -new -newkey <alg:opt> -nodes -out CSR.pem # Generate CSR and new Private Key file
openssl req -x509 -key KEY.pem -out CERT.pem # Generate Certificate with existing Private Key file
openssl req -x509 -newkey <alg:opt> -nodes -out CERT.pem # Generate Certificate and new Private Key file
openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key # Generate a new private key and Certificate Signing Request
The path to the cnf file needs to be defined for your windows environment.
SET OPENSSL_CONF=z:\<path to openssl>\openssl.cnf
https://mediatemple.net/community/products/dv/360038646712/generating-a-san-ssl-csr
app.cnf:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
stateOrProvinceName = State or Province Name (full name)
localityName = Locality Name (eg, city)
organizationName = Organization Name (eg, company)
organizationalUnitName = Organization Unit Name (eg, company unit)
commonName = Common Name (e.g. server FQDN or YOUR name)
emailAddress = E-mail address
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
openssl req -new -sha256 -nodes -out <csr name>.csr -newkey rsa:2048 -keyout <key file name>.key -config <path to config file>.cfg
openssl req -new -newkey rsa:2048 -nodes -keyout app.key -out app.csr -config app.cnf
Generate a self-signed certificate (see How to Create and Install an Apache Self Signed Certificate for more info)
openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout privateKey.key -out certificate.crt
Generate a certificate signing request (CSR) for an existing private key
openssl req -out CSR.csr -key privateKey.key -new
Generate a certificate signing request based on an existing certificate
openssl x509 -x509toreq -in certificate.crt -out CSR.csr -signkey privateKey.key
Remove a passphrase from a private key
openssl rsa -in privateKey.pem -out newPrivateKey.pem
san.cf:
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = v3_req
[req_distinguished_name]
countryName = Country Name (2 letter code)
countryName_default = US
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = OR
localityName = Locality Name (eg, city)
localityName_default = Portland
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = example
commonName = example.org
commonName_max = 64
[ v3_req ]
# Extensions to add to a certificate request
basicConstraints = CA:FALSE
subjectAltName = @alt_names
[alt_names]
DNS.1 = private-registry.localdomain
DNS.2 = localhost.localdomain
DNS.3 = localhost
IP.1 = 127.0.0.1
openssl req -out sslcert.csr -newkey rsa:2048 -nodes -keyout domain.key -config san.cnf
openssl req -noout -text -in sslcert.csr | grep DNS
openssl x509 -signkey domain.key -in sslcert.csr -req -days 3650 -out domain.crt
openssl x509 -in CERT.pem -noout -text # Viewing x509 Certificate as human readable Text
openssl req -in CSR.pem -noout -text # Viewing Certificate Signing Request (CSR) contents as Text
openssl req -text -noout -verify -in CSR.csr # Check a Certificate Signing Request (CSR)
openssl rsa -in privateKey.key -check # Check a private key
Extract specific pieces of information from x509 Certificates
openssl x509 -in certificate.crt -text -noout
openssl x509 -in certificate.pem -text
openssl x509 -in CERT.pem -noout -dates
openssl x509 -in CERT.pem -noout -issuer –subject
Other items you can extract: -modulus -pubkey -ocsp_uri -ocspid -serial -startdate -enddate
Extract specific Extension(s) from a certificate
openssl x509 -in CERT.pem -noout -ext subjectAltName
openssl x509 -in CERT.pem -noout -ext authorityInfoAccess,crlDistributionPoints
Other extensions you can extract: basicConstraints nameConstraints certificatePolicies keyUsage extendedKeyUsage subjectKeyIdentifier authorityKeyIdentifier Extract all Extensions from a certificate
openssl x509 -in CERT.pem -noout -text | sed '/X509v3 extensions/,/Signature Algorithm:/!d'
Check a PKCS#12 file (.pfx or .p12)
openssl pkcs12 -info -in keyStore.p12
openssl x509 -in FILE # To check if file is PEM format
openssl x509 -in FILE -inform DER # To check if file is DER format
openssl pkcs12 -in FILE -nodes # To check if file is PFX format
To check, or convert, PEM or DER Key Files use openssl pkey
instead of openssl x509 and same command arguments.
openssl x509 -in CERT.pem -outform DER -out CERT.der # Convert PEM Certificate file to DER
openssl x509 -in CERT.der -inform der -out CERT.pem # Convert DER Certificate file (.crt .cer .der) to PEM
openssl pkcs12 -in CERTS.pem -nokeys -export -out CERTS.pfx # Convert PEM Certificate(s) to PFX
openssl pkcs12 -export -in mykeycertificate.pem.txt -out mykeystore.pkcs12 -name myAlias -noiter -nomaciter # Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12) with alias
To include a key in PFX file use -inkey KEY.pem instead of -nokeys
The generated KeyStore is mykeystore.pkcs12 with an entry specified by the myAlias alias. This entry contains the private key and the certificate provided by the -in argument. The noiter and nomaciter options must be specified to allow the generated KeyStore to be recognized properly by JSSE.
openssl pkcs12 -in FILE.pfx -out EVERYTHING.pem -nodes # To extract everything within a PFX file as a PEM file
openssl pkcs12 -in FILE.pfx -out KEY.pem -nodes -nocerts # To extract only the Private Key from a PFX file as PEM
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes # Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt # You can add -nocerts to only output the private key or add -nokeys to only output the certificates. Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)
PFX files can contain Certificate(s), or Certificate(s) + one matching Key
-
-clcerts
- extract only end-entity certificate (client certificate) -
-cacerts
- extract all but end-entity certificate -
-nokeys
- extract only certficiates
check Diffie-Hellman primes via:
openssl dhparam -in dhparams.pem -text -noout
dhparams.pem can be generated by
openssl dhparam -out dhparams.pem 2048
openssl dhparam -dsaparam -out dhparam.pem 4096
format uzywany w java dbviewer dla klucza klienta ssl wymaga formatu pksc8
openssl pkcs8 -topk8 -inform PEM -outform DER -nocrypt -in client-key.pem -out client-key.pk8
- https://www.sslshopper.com/ssl-checker.html verify that an SSL certificate is installed correctly,
- https://www.sslshopper.com/csr-decoder.html verify CSR
- https://www.sslshopper.com/ssl-converter.html converter
openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in privateKey.key | openssl md5
openssl req -noout -modulus -in CSR.csr | openssl md5
openssl s_client -connect www.paypal.com:443
openssl s_client -showcerts \
-connect catalog.istioinaction.svc.cluster.local:80 \
-CAfile /var/run/secrets/istio/root-cert.pem | \
openssl x509 -in /dev/stdin -text -noout
openssl verify -CAfile /var/run/secrets/istio/root-cert.pem \
<(openssl s_client -connect \
catalog.istioinaction.svc.cluster.local:80 -showcerts 2>/dev/null)
openssl s_client -showcerts -connect www.mwl.io:443 \
</dev/null | openssl x509 -text -noout
The openssl s_client
command serves as a TLS-aware netcat,
negotiating a TLS connection with the host and port you specify.
This command normally waits for input, but we feed it /dev/null
so
that it doesn’t wait. The -showcerts
option displays the certificate
information, and -connect
lets you choose your target. We pipe this
into openssl x509, the X.509 parser, specify that we want human-
friendly output with -text
, and skip showing the encoded certificate
with -noout
.
This combination grabs a web site’s TLS certificate and displays the contents. It’s the Unix equivalent of clicking on the lock icon in the browser’s address bar and navigating a few layers of menu to find “Show Certificate.”
The s_client command was written for debugging TLS connections.
When it discovers invalid certificates, it defaults to accepting them and
continuing on. If you’re relying on OpenSSL to expose TLS problems,
add the -verify_return_error
flag to all of your s_client
commands. If you’re investigating a daemon or application protocol
problem within the TLS wrapping, you could skip this flag.
$ openssl s_client -verify_return_error \
-connect imap.gmail.com:995
Use s_client to talk directly to the TCP port dedicated to TLS-wrapped POP3. The -connect
argument tells s_client to create a TLS tunnel to the given host and port.
$ openssl s_client -verify_return_error -crlf www.mwl.io:443
$ openssl s_client -crlf -verify_return_error -connect www.mwl.io:443 # older OpenSSL or LibreTLS, use both -crlf and -connect
The s_client command takes the SNI server name from the name of the host you connect to. If you must specify a different SNI server name, use the -servername option. Here, I want to be sure that my installation of my web site on a new server works, even though it’s on a temporary hostname.
$ openssl s_client -servername www.mwl.io \
-crlf newwww.mwl.io:443
Flags:
-
-quiet
flag to silence everything except a summary of the certificate chain -
-brief
to see a summary of the negotiated TLS characteristics -
-ign_eof
flag is intended to keep a TLS connection alive even after the end of any input. It has the side effect of disabling these commands. -
-tls1_3 -tls1_2 -tls1_1 -tls1 -ssl3
force use of a particular TLS version -
-no_ssl3, -no_tls1, -no_tls1_1,-no_tls1_2, or -no_tls1_3
forbid s_client from using TLS version . Use many flag to forbit more version
# server side:
openssl s_server -accept 4433 -cert server.crt -key server.key
# client side
openssl s_client -connect server_ip:4433 # open client console
retr < your_file.txt # in client console
cat > received_file.txt # in server side
on Linux, you can get secure random bytes from a / dev/random device
$ xxd -plain -len 32 -cols 32 /dev/random
If you want to generate secure random bytes in your C code, OpenSSL provides the RAND_bytes() function, which uses an OS-dependent cryptographically secure pseudorandom generator (CSPRNG) and will provide you with the requested amount of secure random bytes. You can also use that function on the command line using the openssl rand command:
$ openssl rand -hex 32
The obtained encryption key can be used for symmetric encryption. It must also be saved in a safe place or securely transmitted to the decrypting party in order to decrypt the ciphertext later.
# generate a sample file
$ seq 1000 >somefile.txt
we are choosing the following parameters for our encryption:
- Cipher: AES-256
- Operation mode: CBC (we should have chosen GCM, but that mode is not supported by the command-line tool)
- Padding type: standard block padding
$ man openssl
$ man openssl-enc
$ man openssl-rand
We see that the enc subcommand needs an encryption key and IV, among other parameters. We can just generate those values randomly with the rand subcommand.
# let’s generate a 256-bit encryption key using our recently acquired knowledge:
$ openssl rand -hex 32
74c8a19fee9e0710683afe526462ce8a960ca1356e113bf3a08736a68a48eca0
# We also need to generate a 128-bit IV, the same length as the block size:
$ openssl rand -hex 16
4007fbd36f08cb04869683b1f8a15c99
# Finally, let’s encrypt some files:
$ openssl enc \
-aes-256-cbc \
–K \
74c8a19fee9e0710683afe526462ce8a960ca1356e113bf3a08736a68a48eca0
\
-iv 4007fbd36f08cb04869683b1f8a15c99 \
-e \
-in somefile.txt \
-out somefile.txt.encrypted
# Let’s try to decrypt the file:
$ openssl enc \
-aes-256-cbc \
-K
74c8a19fee9e0710683afe526462ce8a960ca1356e113bf3a08736a68a48eca0
\
-iv 4007fbd36f08cb04869683b1f8a15c99 \
-d \
-in somefile.txt.encrypted \
-out somefile.txt.decrypted
Weryfication:
$ cksum somefile.txt*
on Windows and do not have the cksum command
$ openssl dgst somefile.txt*
$ openssl enc \
-aes-256-cbc \
-K
00c8a19fee9e0710683afe526462ce8a960ca1356e113bf3a08736a68a48eca0
\
-iv 4007fbd36f08cb04869683b1f8a15c99 \
-d \
-in somefile.txt.encrypted \
-out somefile.txt.decrypted
bad decrypt
140283139302720:error:06065064:digital envelope
routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/
evp/evp_enc.c:610:
It is the standard padding that helped! The decryption of the last block resulted in a block of garbage data, which did not have the right dding at the end, and openssl detected that.
Let’s try to decrypt our file in CTR mode - tried to decrypt with the wrong key and in the wrong mode!:
$ openssl enc \
-aes-256-ctr \
-K
00c8a19fee9e0710683afe526462ce8a960ca1356e113bf3a08736a68a48eca0
\
-iv 4007fbd36f08cb04869683b1f8a15c99 \
-d \
-in somefile.txt.encrypted \
-out somefile.txt.decrypted
No output, meaning that openssl did not detect any errors. Note the size of somefile.txt.decrypted: 3904, the same size as somefile.txt.encrypted. The checksums of somefile.txt and somefile.txt.decrypted are different, as expected.
$ man openssl-dgst # show documentation
$ seq 20000 >somefile.txt # generate test file
$ openssl dgst –list # list digest algorithms are supported
$ openssl dgst -sha3-256 somefile.txt
SHA3-256(somefile.txt)=
658656e129914052546af527ba8cf573ab27fb47551a0682ffcf00eeaf5...
The openssl tool provides two methods of HMAC calculation:
- openssl dgst
- openssl mac ( from OpenSSL 3.0)
$ seq 20000 >somefile.txt
$ openssl rand -hex 32 # generate secret password
df036c471b612f8ad099078d8e3bd9c64339e7aeab56ec75e2222c415db..
$ openssl dgst -sha-256 -mac HMAC -macopt \
hexkey:df036c471b612f8ad099078d8e3bd9c64339e7aeab56ec75e2222c415db113de \
somefile.txt
HMAC-SHA256(somefile.txt)=
55e18ba91be755133ab0f4dbca5d06f2e7df0b6bb4cd5f16f9f2d2f7cf8
###
$ openssl mac -digest SHA-256 –macopt \
hexkey:df036c471b612f8ad099078d8e3bd9c64339e7aeab56ec75e2222c415db113de \
-in somefile.txt \
HMAC
55E18BA91BE755133AB0F4DBCA5D06F2E7DF0B6BB4CD5F16F9F2D2F7CF8
A Key Derivation Function (KDF) is a function that derives a secret key of the desired bit length from some other secret material, such as a password, a passphrase, another shared secret, or a combination of asymmetric private and public keys. That other secret material is also called Input Key Material (IKM), while the secret key produced is also called Output Key Material (OKM). IKM and OKM often have different lengths.
A Password-Based Key Derivation Function (PBKDF) is a KDF designed to produce secret keys from low-entropy IKMs, such as passwords. Those secret keys can be used as symmetric encryption keys. Another popular application of PBKDFs is password hashing. PBKDFs provide more brute- force-resistant password hashing than cryptographic hash functions alone.
$ man openssl-kdf # kdf function added in OpenSSL 3.0
$ openssl rand -hex 16 # generate salt
cf0e0acf943629ecffea41c87bab94d4
$ $ openssl kdf \
-keylen 32 \
-kdfopt 'pass:SuperPa$$w0rd' \
-kdfopt hexsalt:cf0e0acf943629ecffea41c87bab94d4 \
-kdfopt n:65536 -kdfopt r:8 -kdfopt p:1 \
SCRYPT
D0:3D:31:A1:A2:2A:F6:68:99:B3:02:22:60:3B:D7:21:5B:15:5B:80
Note that the command-line argument containing the
password is enclosed in single quotes. This is to avoid the
special interpretation of $ characters by the command
interpreter. Another method of passing special characters in a
password would be to pass a hex-encoded password using the
-kdfopt hexpass:
option instead of -kdfopt pass:
.
Most software expects to find certificates in /etc/ssl/certs. OpenSSL expects to find them in a certs subdirectory of the system OpenSSL directory (available by running openssl version -a).
Each Unix also has their own way to manage these
certificates. Maybe it’s certctl
, or add-trusted-cert
, or
update-ca-certificates
, or a tangle of OpenSSL commands. If
you need to add or remove certificates from the OpenSSL trust store,
check your operating system documentation for the correct way to
do so.
If you want to use a specific CA certificate in an OpenSSL
command—say, for testing a private CA—you can use the -CAfile
option to point at the certificate file.
openssl x509 -enddate -noout -in ścieżka/do/twojego/certyfikatu.pem
cat certyfikat.base64 | base64 -d | openssl x509 -enddate -noout
xclip -o -selection clipboard | base64 -d | openssl x509 -enddate -noout
xsel -b | base64 -d | openssl x509 -enddate -noout