# OpenSSL Common Usage

[OpenSSL](https://www.madboa.com/geek/openssl/) is a powerful Linux command for managing certificates. These are some common operations I frequently use.

# Generate RSA Key Pair
This command generates a 2048 bits private key.

```bash
openssl genrsa -out example.key 2048
```
Verify private and public key by comparing the output of the following 2 commands.

```bash
ssh-keygen -yef id_rsa
ssh-keygen -yef id_rsa.pub
```

# Generate Certificate Signing Request (CSR) With Existing Key

CSR is generated from existing private key. Make sure you keep your private key well.

```bash
openssl req -out example.csr -key example.key -new
```

# Generate New Key And Certificate Signing Request (CSR)

Generate a new private key and new CSR using that key.

```bash
openssl req -new -newkey rsa:2048 -nodes -keyout example.key -out example.csr
```

# Check Certificate Signing Request (CSR) Info

```bash
openssl req -in example.csr -noout -text
```

# Generate Self-signed SSL Cert

Both private key and CSR are needed to generate SSL cert. Choose an appropriate expiry date for your cert.

```bash
openssl x509 -req -days 3650 -in example.csr -signkey example.key -out example.crt
```

# Generate PKCS12 Cert From PEM Cert And Private Key

Note that the CA bundle file is needed for the `certfile` switch. `certfile` switch is optional.

```bash
openssl pkcs12 -export -out example.pfx -inkey example.key -in example.crt -certfile CACert.crt
```

# Generate PKCS7 Cert To PEM Cert

```bash
openssl pkcs7 -print_certs -in certificate.p7b -out certificate.pem
```

# Check Cert Information

This is referring to x509 certs, which is used by Apache for SSL.

```bash
openssl x509 -in example.crt  -text
```

View a certificate encoded in [PKCS#7](https://knowledge.digicert.com/generalinformation/INFO4448.html) format

```bash
openssl pkcs7 -print_certs -in example.p7b
```

View a certificate and key pair encoded in [PKCS#12](https://knowledge.digicert.com/generalinformation/INFO4448.html) format

```bash
openssl pkcs12 -info -in example.pfx
```

# Verification

RSA private key is used to generate CSR and cert. Verification can be performed by matching modulus that is embedded in key, CSR, and cert.

Get hashed modulus of key

```bash
openssl rsa -in example.key -noout -modulus | md5sum
```

# "unable to load private key" Issue
If you are getting "unable to load private key" issue, and the first line in key file is `-----BEGIN OPENSSH PRIVATE KEY-----` instead of `-----BEGIN RSA PRIVATE KEY-----`, there is a workaround. Use the following command to convert it to regular REM format.

```bash
ssh-keygen -p -m PEM -f example.key
```

Get hashed modulus of CSR

```bash
openssl req -in example.csr -noout -modulus | md5sum
```

Get hashed modulus of cert

```bash
openssl x509 -in example.crt -noout -modulus | md5sum
```
