Skip to content

Instantly share code, notes, and snippets.

@mohanpedala
Last active November 7, 2025 18:27
Show Gist options
  • Select an option

  • Save mohanpedala/468cf9cef473a8d7610320cff730cdd1 to your computer and use it in GitHub Desktop.

Select an option

Save mohanpedala/468cf9cef473a8d7610320cff730cdd1 to your computer and use it in GitHub Desktop.

Revisions

  1. mohanpedala revised this gist Nov 3, 2021. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -32,7 +32,6 @@
    + [Check Hashing Algorithm](#check-hashing-algorithm)
    + [Extract only the Hashing Algorithm](#extract-only-the-hashing-algorithm)
    + [Extract a server certificate](#extract-a-server-certificate)
    - [[Generating SSL Certificates using Let's Encrypt](https://gist.github.com/mohanpedala/3e5a9ab87ee4b58b5eff2e45b8af2584)](#-generating-ssl-certificates-using-let-s-encrypt--https---gistgithubcom-mohanpedala-3e5a9ab87ee4b58b5eff2e45b8af2584-)

    ## Generate a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.
  2. mohanpedala revised this gist Nov 3, 2021. 1 changed file with 49 additions and 13 deletions.
    62 changes: 49 additions & 13 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,39 @@
    * [Generate a private key and a CSR(Certificate Signing Request )](#generate-a-private-key-and-a-csr-certificate-signing-request--)
    * [Generate a CSR from an Existing Private Key](#generate-a-csr-from-an-existing-private-key)
    * [Generate a CSR from an Existing Certificate and Private Key](#generate-a-csr-from-an-existing-certificate-and-private-key)
    * [Generating SSL Certificates](#generating-ssl-certificates)
    + [Generate a Self-Signed Certificate](#generate-a-self-signed-certificate)
    + [Generate a Self-Signed Certificate from an Existing Private Key](#generate-a-self-signed-certificate-from-an-existing-private-key)
    + [Generate a Self-Signed Certificate from an Existing Private Key and CSR](#generate-a-self-signed-certificate-from-an-existing-private-key-and-csr)
    + [View Certificates](#view-certificates)
    + [View CSR Entries](#view-csr-entries)
    - [View Certificate Entries](#view-certificate-entries)
    - [Verify a Certificate was Signed by a CA](#verify-a-certificate-was-signed-by-a-ca)
    * [Private Keys](#private-keys)
    - [Create a Private Key](#create-a-private-key)
    + [Verify a Private Key](#verify-a-private-key)
    + [Verify a Private Key Matches a Certificate and CSR](#verify-a-private-key-matches-a-certificate-and-csr)
    + [Encrypt a Private Key](#encrypt-a-private-key)
    + [Decrypt a Private Key](#decrypt-a-private-key)
    * [Reference](#Referance)
    - [Java keytool](#java-keytool)
    * [TrustStore vs keyStore:](#truststore-vs-keystore-)
    + [Starting the application server with the keystores](#starting-the-application-server-with-the-keystores)
    * [Create a Truststore](#create-a-truststore)
    * [Update keystore with a certificate](#update-keystore-with-a-certificate)
    * [Delete keystore cert](#delete-keystore-cert)
    * [List keystore](#list-keystore)
    * [Delete a certificate from a Java Keytool keystore](#delete-a-certificate-from-a-java-keytool-keystore)
    * [Change a Java keystore password](#change-a-java-keystore-password)
    * [Export a certificate from a keystore](#export-a-certificate-from-a-keystore)
    * [Check a stand-alone certificate](#check-a-stand-alone-certificate)
    * [Generate a Java keystore and key pair](#generate-a-java-keystore-and-key-pair)
    + [Options](#options)
    + [Check Hashing Algorithm](#check-hashing-algorithm)
    + [Extract only the Hashing Algorithm](#extract-only-the-hashing-algorithm)
    + [Extract a server certificate](#extract-a-server-certificate)
    - [[Generating SSL Certificates using Let's Encrypt](https://gist.github.com/mohanpedala/3e5a9ab87ee4b58b5eff2e45b8af2584)](#-generating-ssl-certificates-using-let-s-encrypt--https---gistgithubcom-mohanpedala-3e5a9ab87ee4b58b5eff2e45b8af2584-)

    ## Generate a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

    @@ -38,46 +74,46 @@ Email Address []:</pre></code>
    Non interactively answer CSR
    <pre><code>-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"</pre></code>

    # Generate a CSR from an Existing Private Key
    ## Generate a CSR from an Existing Private Key
    This command creates a new CSR (domain.csr) based on an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -out domain.csr</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -key option specifies an existing private key (domain.key) that will be used to generate a new CSR.
    2. -new option indicates that a CSR is being generated.

    # Generate a CSR from an Existing Certificate and Private Key
    ## Generate a CSR from an Existing Certificate and Private Key
    This command creates a new CSR (domain.csr) based on an existing certificate (domain.crt) and private key (domain.key):
    <pre><code>openssl x509 -in domain.crt -signkey domain.key -x509toreq -out domain.csr</pre></code>
    The -x509toreq option specifies that you are using an X509 certificate to make a CSR.

    ## Generating SSL Certificates
    # Generate a Self-Signed Certificate
    ### Generate a Self-Signed Certificate
    This command creates a 2048-bit private key (domain.key) and a self-signed certificate (domain.crt) from scratch:
    <pre><code>openssl req -newkey rsa:2048 -nodes -keyout domain.key -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -x509 option tells req to create a self-signed cerificate.
    2. -days 365 option specifies that the certificate will be valid for 365 days. A temporary CSR is generated to gather information to associate with the certificate.

    # Generate a Self-Signed Certificate from an Existing Private Key
    ### Generate a Self-Signed Certificate from an Existing Private Key
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.
    1. -x509 option tells req to create a self-signed cerificate.
    2. 365 option specifies that the certificate will be valid for 365 days.
    3. -new option enables the CSR information prompt.

    # Generate a Self-Signed Certificate from an Existing Private Key and CSR
    ### Generate a Self-Signed Certificate from an Existing Private Key and CSR
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key) and (domain.csr):
    <pre><code>openssl x509 -signkey domain.key -in domain.csr -req -days 365 -out domain.crt</pre></code>

    # View Certificates
    ### View Certificates
    Certificate and CSR files are encoded in PEM format, which is not readily human-readable.

    This section covers OpenSSL commands that will output the actual entries of PEM-encoded files.

    # View CSR Entries
    ### View CSR Entries
    This command allows you to view and verify the contents of a CSR (domain.csr) in plain text:
    <pre><code>openssl req -text -noout -verify -in domain.csr</pre></code>
    # View Certificate Entries
    @@ -93,12 +129,12 @@ Use this command to create a password-protected, 2048-bit private key (domain.ke
    <pre><code>openssl genrsa -des3 -out domain.key 2048</pre></code>
    Enter a password when prompted to complete the process.

    # Verify a Private Key
    ### Verify a Private Key
    Use this command to check that a private key (domain.key) is a valid key:
    <pre><code>openssl rsa -check -in domain.key</pre></code>
    If your private key is encrypted, you will be prompted for its pass phrase. Upon success, the unencrypted key will be output on the terminal.

    # Verify a Private Key Matches a Certificate and CSR
    ### Verify a Private Key Matches a Certificate and CSR
    Use these commands to verify if a private key (domain.key) matches a certificate (domain.crt) and CSR (domain.csr):
    <pre><code>
    openssl rsa -noout -modulus -in domain.key | openssl md5
    @@ -107,17 +143,17 @@ openssl req -noout -modulus -in domain.csr | openssl md5
    </pre></code>
    If the output of each command is identical there is an extremely high probability that the private key, certificate, and CSR are related.

    # Encrypt a Private Key
    ### Encrypt a Private Key
    This takes an unencrypted private key (unencrypted.key) and outputs an encrypted version of it (encrypted.key):
    <pre><code>
    openssl rsa -des3 -in unencrypted.key -out encrypted.key</pre></code>
    Enter your desired pass phrase, to encrypt the private key with.
    # Decrypt a Private Key
    ### Decrypt a Private Key
    This takes an encrypted private key (encrypted.key) and outputs a decrypted version of it (decrypted.key):
    <pre><code>openssl rsa -in encrypted.key -out decrypted.key</pre></code>
    Enter the pass phrase for the encrypted key when prompted.

    Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
    #### Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)

    -----------------------------------------------------------------
    * To Show the certificate
    @@ -240,4 +276,4 @@ openssl x509 -noout -text -in example.crt | grep "Signature Algorithm" | uniq
    openssl s_client -showcerts -connect <HOST_IP>:443
    ```

    ### [Generating SSL Certificates using Let's Encrypt](https://gist.github.com/mohanpedala/3e5a9ab87ee4b58b5eff2e45b8af2584)
    ### [Generating SSL Certificates using Let's Encrypt](https://gist.github.com/mohanpedala/3e5a9ab87ee4b58b5eff2e45b8af2584)
  3. Mohan P Edala revised this gist Aug 11, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    ## Generating a private key and a CSR(Certificate Signing Request )
    ## Generate a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:
  4. Mohan P Edala revised this gist Aug 11, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    ## Genereating a private key and a CSR(Certificate Signing Request )
    ## Generating a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:
  5. Mohan P Edala revised this gist Jul 26, 2019. 1 changed file with 4 additions and 0 deletions.
    4 changes: 4 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -235,5 +235,9 @@ openssl x509 -noout -text -in example.crt
    ```
    openssl x509 -noout -text -in example.crt | grep "Signature Algorithm" | uniq
    ```
    ##### Extract a server certificate
    ```
    openssl s_client -showcerts -connect <HOST_IP>:443
    ```

    ### [Generating SSL Certificates using Let's Encrypt](https://gist.github.com/mohanpedala/3e5a9ab87ee4b58b5eff2e45b8af2584)
  6. Mohan P Edala revised this gist Jul 24, 2019. 1 changed file with 10 additions and 0 deletions.
    10 changes: 10 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -158,6 +158,16 @@ openssl pkcs12 -in example.com.pfx -out example.com.pem -nodes
    ```
    openssl pkcs12 -export -name example.com.pfx -out example.com.pfx -in example.com.pem
    ```
    or
    ```
    openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt
    ```
    - The key file is just a text file with your private key in it.

    - If you have a root CA and intermediate certs, then include them as well using multiple -in params
    ```
    openssl pkcs12 -export -out domain.name.pfx -inkey domain.name.key -in domain.name.crt -in intermediate.crt -in rootca.crt
    ```
    --------------------------------------------------------------

    ### Java keytool
  7. Mohan P Edala revised this gist Apr 22, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache H
    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:

    ```
    openssl req -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr</code></pre>
    openssl req -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr
    ```

    Creating a 2048-bit private key and public key
  8. Mohan P Edala revised this gist Mar 22, 2019. 1 changed file with 4 additions and 2 deletions.
    6 changes: 4 additions & 2 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    # Genereating a private key and a CSR(Certificate Signing Request )
    ## Genereating a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:
    @@ -224,4 +224,6 @@ openssl x509 -noout -text -in example.crt
    ##### Extract only the Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt | grep "Signature Algorithm" | uniq
    ```
    ```

    ### [Generating SSL Certificates using Let's Encrypt](https://gist.github.com/mohanpedala/3e5a9ab87ee4b58b5eff2e45b8af2584)
  9. Mohan P Edala revised this gist Mar 20, 2019. 1 changed file with 227 additions and 371 deletions.
    598 changes: 227 additions & 371 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -1,371 +1,227 @@
    ### Virtual Host and Serving Static Content

    * Default path: vim /etc/nginx/conf.d/default.conf
    * Custom Config vim /etc/nginx/conf.d/example.com.conf

    * Default index.html: /usr/share/nginx/html/index.html
    * Custom index.html: /var/www/example.com/html/index.html
    - Path explanation:
    - Default path : /var/www/
    - Virtualhostname : example.com

    * Test Configuration of the server
    ```
    nginx -t
    ```
    * Test Ouput:
    ```
    curl localhost
    ```
    * Test Configuration of a different hosts/virtualservers
    ```
    curl --header "Host: example.com" localhost
    ```
    * Troubleshooting:
    - Error 403:
    ```
    [root@dimpastra1 nginx]# curl --header "Host: example.com" localhost
    <html>
    <head><title>403 Forbidden</title></head>
    <body bgcolor="white">
    <center><h1>403 Forbidden</h1></center>
    <hr><center>nginx/1.14.2</center>
    </body>
    </html>
    ```
    - Solution: Check the error logs
    - Reason is due to selinux security
    ```
    less /var/log/nginx/error.log
    2019/03/19 21:30:49 [error] 30362#30362: *13 "/var/www/example.com/html/index.html" is forbidden (13: Permission denied), client: 127.0.0.1, server: example.com, request: "GET / HTTP/1.1", host: "example.com"
    ```
    * Check if proper permission exsists to display the content
    ```
    semanage fcontext -l | grep /usr/share/nginx/html
    semanage fcontext -a -t httpd_sys_content_t '/var/www/(/.*)?'
    semanage fcontext -l | grep /var/www
    ```
    * To get the proper permissions to use the virtulhosts
    ```
    restorecon -R -v /var/www
    ```
    ### Error pages for Default Hosts
    * To add error messages
    ```
    vim /etc/nginx/conf.d/default.conf
    ```
    ```
    server {
    listen 80 default_server;
    server_name _;
    root /usr/share/nginx/html;
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Create html pages for errors at the below location
    ```
    vim /usr/share/nginx/html/404.html
    ```
    ### Access Control with HTTP Basic Auth
    * HTTP basic authentication allows us to require a username and password before we allow a user to access a specific URL. To set up NGINX with HTTP basic auth, we’ll be using the auth_basic module. We can specify that specific location blocks utilize basic auth while others do not. Let’s create a new location block that will prevent a specific HTML file from being accessible:
    ```
    vim etc/nginx/conf.d/default.conf
    ```
    ```
    server {
    listen 80 default_server;
    server_name _;
    root /usr/share/nginx/html;
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * The location = /admin.html is how we specify what should happen if someone navigates to the /admin.html path and it matches exactly. From there, we’re able to specify a value for auth_basic using a string (any string will do), and we give the path to the file containing the username/password pairs that have access.
    * Create the admin.html
    ```
    [root] $ echo "<h1>Admin Page</h1>" > /usr/share/nginx/html/admin.html
    ```
    * Generating a Password File
    - Our configuration is currently valid, but we don’t have a password file to work with yet. We’re going to install the httpd-tools to create our .htpasswd file:
    ```
    yum install -y httpd-tools
    ```
    * now have access to the htpasswd utility that can generate a file for us with encrypted passwords for our users
    ```
    [root] $ htpasswd -c /etc/nginx/.htpasswd admin
    New password:
    Re-type new password:
    Adding password for user admin
    ```
    * Test the configuration
    ```
    systemctl reload nginx
    [root@dimpastra1 nginx]# curl localhost/admin.html
    <html>
    <head><title>401 Authorization Required</title></head>
    <body bgcolor="white">
    <center><h1>401 Authorization Required</h1></center>
    <hr><center>nginx/1.14.2</center>
    </body>
    </html>
    ```
    * se the -u flag for curl, then we can pass in the username and password divided by a
    ```
    [root@dimpastra1 nginx]# curl -u admin:****** localhost/admin.html
    <h1>ADMIN PAGE</h1>
    ```
    ### NGINX Security
    * Create SSL certificate using [openssl](https://gist.github.com/mohanpedala/468cf9cef473a8d7610320cff730cdd1)
    * Configuring the Host for SSL/TLS/HTTPS using Nginx http module, server directive, ssl module.
    * Configure https server
    ```
    server {
    listen 80 default_server;
    <b> listen 443 ssl; </b>
    server_name _;
    root /usr/share/nginx/html;
    <b> ssl_certificate /etc/nginx/ssl/public.pem; </b>
    <b> ssl_certificate_key /etc/nginx/ssl/private.key;</b>
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Test connection
    ```
    curl -k https://localhost
    ```
    ### Rewrite rules (Cleaning Up URLs)
    * Documentation
    - NGINX http module
    - NGINX server directive
    - NGINX try_files directive
    - NGINX rewrite directive
    * Remove .html at the end of our files. To remove this, we’re going to utilize the rewrite and try_files directives.
    * Convert URLs using a rewrite rule. Going to /admin.html should redirect to /admin.
    * Use try_files to ensure that we're rendering the proper page or rendering a 404.
    ```
    vim /etc/nginx/conf.d/default.conf
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    // added rewrite directive
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Rewrite rules follow the regex pattern.
    ```
    rewrite REGEX REPLACEMENT [flag];
    ```
    * Regex break down
    ```
    ^(/.*)\.html(\?.*)?$
    ```
    - The starting ```^``` indicates that we’re going from the very beginning of the URI. We create a capture group using parentheses.
    - The pattern ```/.*``` means starting with a ```/``` and including all characters after that.
    - Next, we expect to find a ```.html``` (notices that we needed to escape it using a ```)```.
    - Lastly, we create another capture group that gets an optional query string (anything after a ?) until the end of the URI (as indicated by the $ character).
    - The capture groups will be usable in the REPLACEMENT portion of the direction using ```$1, $2, etc```.
    * Reload the server
    ```
    systemctl reload nginx
    ```
    * Test it by opening a browser and hit the nginx server public ip.
    * we’ll run into an infinite redirect loop. This is happening because we’re even reloading the 404.html page so we can’t even render that properly. To fix this redirect loop, we’ll need to use try_files.
    ```
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    // added try_files
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404; // added try_files
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    Explanation:
    - We’ve added a try_files directive to both of our location blocks with slightly different rules. We want to be able to handle someone going to the index.html within potentially nested directories.
    - The try_files call will look for the first file (or directory) that matches the request moving from left to right. If nothing is found, then the rightmost file or status code will be returned.
    * Reload the server configuration and try to navigate to the root URL or the status page, we will now see the content.
    * Unfortunately, we appear not to be hitting our HTTP basic authentication anymore.
    * Reason for this is that the $uri is changed before we process the location blocks and we’re never going to have a $uri that matches /admin.html. We need to change that location check to match against /admin instead.
    ```
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = /admin { //removed .html
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    ### Redirecting All Traffic to HTTPS
    * Documentation
    - NGINX http module
    - NGINX server directive
    - NGINX return directive
    - NGINX $request_uri variable
    - NGINX $host variable
    * Seperate the HTTP and HTTPS handling for our server by creating two separate server blocks. One will listen on port 80 and not display any content. The other will hold our current configuration but only listen on port 443.
    * Here’s what our configuration looks like with them divided out:
    ```
    vim /etc/nginx/conf.d/default.conf
    // Seperate server block to listen on port 80 and not display any content
    server {
    listen 80 default_server;
    server_name _;
    return 404;
    }
    server {
    listen 443 ssl default_server;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = /admin {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Test visit our IP address with http://, we should receive a 404 error, but if we visit the same page with https:// we’ll see the content that we expect.
    #### Redirecting To Completely Different URL
    * Redirect HTTP traffic, we want to start redirecting the user to the proper page via HTTPS.
    * we have already done using the return directive in the above snippet.
    ```
    return STATUS_CODE URL;
    ```
    * Since we’re doing a redirect, we’re going to use the 301 status code.
    * As for the URL portion of the statement, we’re going to use variables that are present when processing the request to ensure that we go to the proper spot.
    * To ensure that it goes to the proper server we’ll use the $host variable in our destination URL to pass along the domain name.
    * Using $host will make this server redirect to the proper server after we have multiple HTTPS, virtual hosts.
    * We’ll also use the $request_uri variable which represents the path portion of the request.
    * The only other thing that we need to do is start the URL with https://.
    ```
    vim /etc/nginx/conf.d/default.conf
    server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri; // Change using return directive
    }
    server {
    listen 443 ssl default_server;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = /admin {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    * Reload our server and visit the /admin route using http:// we should be redirected to the https:// version of the URL and prompted for our password.
    [For Syntax Reference](http://nginx.org/en/docs/http/ngx_http_core_module.html)
    # Genereating a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:

    ```
    openssl req -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr</code></pre>
    ```

    Creating a 2048-bit private key and public key
    ```
    openssl req -x509 -nodes -days 365 \
    -newkey rsa:2048 \
    -keyout /etc/nginx/ssl/private.key \
    -out /etc/nginx/ssl/public.pem
    ```
    Command Explanation:
    ```
    req - We’re making a certificate request to OpenSSL
    -x509 - Specifying the structure that our certificate should have. Conforms to the X.509 standard
    -nodes - Do not encrypt the output key
    -days 365 - Set the key to be valid for 365 days
    -newkey rsa:2048 - Generate an RSA key that is 2048 bits in size
    -keyout /etc/nginx/ssl/private.key - File to write the private key to
    -out /etc/nginx/ssl/public.pem - Output file for public portion of key
    -new option, which is not included here but implied, indicates that a CSR is being generated.
    ```
    After running the above command answer the CSR information
    <pre><code>
    Country Name (2 letter code) [AU]:US
    State or Province Name (full name) [Some-State]:New York
    Locality Name (eg, city) []:Brooklyn
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Brooklyn Company
    Organizational Unit Name (eg, section) []:Technology Division
    Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
    Email Address []:</pre></code>

    Non interactively answer CSR
    <pre><code>-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"</pre></code>

    # Generate a CSR from an Existing Private Key
    This command creates a new CSR (domain.csr) based on an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -out domain.csr</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -key option specifies an existing private key (domain.key) that will be used to generate a new CSR.
    2. -new option indicates that a CSR is being generated.

    # Generate a CSR from an Existing Certificate and Private Key
    This command creates a new CSR (domain.csr) based on an existing certificate (domain.crt) and private key (domain.key):
    <pre><code>openssl x509 -in domain.crt -signkey domain.key -x509toreq -out domain.csr</pre></code>
    The -x509toreq option specifies that you are using an X509 certificate to make a CSR.

    ## Generating SSL Certificates
    # Generate a Self-Signed Certificate
    This command creates a 2048-bit private key (domain.key) and a self-signed certificate (domain.crt) from scratch:
    <pre><code>openssl req -newkey rsa:2048 -nodes -keyout domain.key -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -x509 option tells req to create a self-signed cerificate.
    2. -days 365 option specifies that the certificate will be valid for 365 days. A temporary CSR is generated to gather information to associate with the certificate.

    # Generate a Self-Signed Certificate from an Existing Private Key
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.
    1. -x509 option tells req to create a self-signed cerificate.
    2. 365 option specifies that the certificate will be valid for 365 days.
    3. -new option enables the CSR information prompt.

    # Generate a Self-Signed Certificate from an Existing Private Key and CSR
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key) and (domain.csr):
    <pre><code>openssl x509 -signkey domain.key -in domain.csr -req -days 365 -out domain.crt</pre></code>

    # View Certificates
    Certificate and CSR files are encoded in PEM format, which is not readily human-readable.

    This section covers OpenSSL commands that will output the actual entries of PEM-encoded files.

    # View CSR Entries
    This command allows you to view and verify the contents of a CSR (domain.csr) in plain text:
    <pre><code>openssl req -text -noout -verify -in domain.csr</pre></code>
    # View Certificate Entries
    This command allows you to view the contents of a certificate (domain.crt) in plain text:
    <pre><code>openssl x509 -text -noout -in domain.crt</pre></code>
    # Verify a Certificate was Signed by a CA
    Use this command to verify that a certificate (domain.crt) was signed by a specific CA certificate (ca.crt):
    <pre><code>openssl verify -verbose -CAFile ca.crt domain.crt</pre></code>
    ## Private Keys
    This section covers OpenSSL commands that are specific to creating and verifying private keys.
    # Create a Private Key
    Use this command to create a password-protected, 2048-bit private key (domain.key):
    <pre><code>openssl genrsa -des3 -out domain.key 2048</pre></code>
    Enter a password when prompted to complete the process.

    # Verify a Private Key
    Use this command to check that a private key (domain.key) is a valid key:
    <pre><code>openssl rsa -check -in domain.key</pre></code>
    If your private key is encrypted, you will be prompted for its pass phrase. Upon success, the unencrypted key will be output on the terminal.

    # Verify a Private Key Matches a Certificate and CSR
    Use these commands to verify if a private key (domain.key) matches a certificate (domain.crt) and CSR (domain.csr):
    <pre><code>
    openssl rsa -noout -modulus -in domain.key | openssl md5
    openssl x509 -noout -modulus -in domain.crt | openssl md5
    openssl req -noout -modulus -in domain.csr | openssl md5
    </pre></code>
    If the output of each command is identical there is an extremely high probability that the private key, certificate, and CSR are related.

    # Encrypt a Private Key
    This takes an unencrypted private key (unencrypted.key) and outputs an encrypted version of it (encrypted.key):
    <pre><code>
    openssl rsa -des3 -in unencrypted.key -out encrypted.key</pre></code>
    Enter your desired pass phrase, to encrypt the private key with.
    # Decrypt a Private Key
    This takes an encrypted private key (encrypted.key) and outputs a decrypted version of it (decrypted.key):
    <pre><code>openssl rsa -in encrypted.key -out decrypted.key</pre></code>
    Enter the pass phrase for the encrypted key when prompted.

    Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)

    -----------------------------------------------------------------
    * To Show the certificate

    openssl s_client -connect example.com:443


    * Import a certificate
    ```
    openssl s_client -connect example.com:443 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > example.com.crt
    ```
    * If you face any issue (Ex: -bash: /dev/null : No such file or directory) try it in the below way

    1. Import the certificate
    ```
    openssl s_client -connect example.com:443 > example.com.txt
    ```
    2. Check if the certificate is present or not
    ```
    cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
    ```
    3. Copy the certificate part to a .crt file
    ```
    cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee example.crt
    ```
    4. verify it
    ```
    cat example.com.crt
    ```
    5. Change the password of a pfx file

    - Export you current certificate to a passwordless pem type
    ```
    openssl pkcs12 -in example.com.pfx -out example.com.pem -nodes
    ```
    - Convert the passwordless pem to a new pfx file with password:
    ```
    openssl pkcs12 -export -name example.com.pfx -out example.com.pfx -in example.com.pem
    ```
    --------------------------------------------------------------

    ### Java keytool

    #### TrustStore vs keyStore:
    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

    [Reference click here](http://www.java67.com/2012/12/difference-between-truststore-vs.html)

    ##### Starting the application server with the keystores
    ```
    -Djavax.net.ssl.keyStore=%CLIENT_CERT%
    -Djavax.net.ssl.keyStorePassword=endeca
    -Djavax.net.ssl.trustStore=%CLIENT_CERT%
    -Djavax.net.ssl.trustStorePassword=endeca
    ```

    #### Create a Truststore

    ```
    keytool -import -alias alias-ofthe-cert -file cert-name.com.cer -storetype JKS -keystore testTruststore
    ```
    #### Update keystore with a certificate

    ```
    keytool -import -file <cert_name>.cer -alias <alias_name_to_identify_inside_truststore.github.com> -keystore <trustorefile_name>
    ```
    #### Delete keystore cert
    ```
    keytool -delete -alias <alias_name_of_the_cert_in_keystore.github.com> -keystore <keystore_name>
    ```
    #### List keystore
    ```
    keytool -list -v -keystore <keystore_name>
    ```
    #### Delete a certificate from a Java Keytool keystore
    ```
    keytool -delete -alias mydomain -keystore keystore.jks
    ```
    #### Change a Java keystore password
    ```
    keytool -storepasswd -new new_storepass -keystore keystore.jks
    ```
    #### Export a certificate from a keystore
    ```
    keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
    ```
    #### Check a stand-alone certificate
    ```
    keytool -printcert -v -file mydomain.crt
    ```
    #### Generate a Java keystore and key pair
    ```
    keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
    ```
    ##### Options
    ```
    -storepass xxxxxx
    ```
    ##### Check Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt
    ```
    ##### Extract only the Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt | grep "Signature Algorithm" | uniq
    ```
  10. Mohan P Edala revised this gist Mar 20, 2019. 1 changed file with 99 additions and 0 deletions.
    99 changes: 99 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -268,5 +268,104 @@
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    ### Redirecting All Traffic to HTTPS
    * Documentation
    - NGINX http module
    - NGINX server directive
    - NGINX return directive
    - NGINX $request_uri variable
    - NGINX $host variable
    * Seperate the HTTP and HTTPS handling for our server by creating two separate server blocks. One will listen on port 80 and not display any content. The other will hold our current configuration but only listen on port 443.
    * Here’s what our configuration looks like with them divided out:
    ```
    vim /etc/nginx/conf.d/default.conf
    // Seperate server block to listen on port 80 and not display any content
    server {
    listen 80 default_server;
    server_name _;
    return 404;
    }
    server {
    listen 443 ssl default_server;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = /admin {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Test visit our IP address with http://, we should receive a 404 error, but if we visit the same page with https:// we’ll see the content that we expect.
    #### Redirecting To Completely Different URL
    * Redirect HTTP traffic, we want to start redirecting the user to the proper page via HTTPS.
    * we have already done using the return directive in the above snippet.
    ```
    return STATUS_CODE URL;
    ```
    * Since we’re doing a redirect, we’re going to use the 301 status code.
    * As for the URL portion of the statement, we’re going to use variables that are present when processing the request to ensure that we go to the proper spot.
    * To ensure that it goes to the proper server we’ll use the $host variable in our destination URL to pass along the domain name.
    * Using $host will make this server redirect to the proper server after we have multiple HTTPS, virtual hosts.
    * We’ll also use the $request_uri variable which represents the path portion of the request.
    * The only other thing that we need to do is start the URL with https://.
    ```
    vim /etc/nginx/conf.d/default.conf
    server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri; // Change using return directive
    }
    server {
    listen 443 ssl default_server;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = /admin {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    * Reload our server and visit the /admin route using http:// we should be redirected to the https:// version of the URL and prompted for our password.
    [For Syntax Reference](http://nginx.org/en/docs/http/ngx_http_core_module.html)
  11. Mohan P Edala revised this gist Mar 20, 2019. 1 changed file with 27 additions and 31 deletions.
    58 changes: 27 additions & 31 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -173,9 +173,9 @@
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    <b> rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;</b>
    // added rewrite directive
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location = /admin.html {
    auth_basic "Login Required";
    @@ -219,15 +219,15 @@
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    <b>location / {
    // added try_files
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }</b>
    }
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    <b> try_files $uri/index.html $uri.html $uri/ $uri =404;</b>
    try_files $uri/index.html $uri.html $uri/ $uri =404; // added try_files
    }
    error_page 404 /404.html;
    @@ -241,36 +241,32 @@
    * Reload the server configuration and try to navigate to the root URL or the status page, we will now see the content.
    * Unfortunately, we appear not to be hitting our HTTP basic authentication anymore.
    * Reason for this is that the $uri is changed before we process the location blocks and we’re never going to have a $uri that matches /admin.html. We need to change that location check to match against /admin instead.
    ```html highlight="my_highlight"
    ```
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location = /admin <!-- my_highlight --> {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    location = /admin { //removed .html
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    [For Syntax Reference](http://nginx.org/en/docs/http/ngx_http_core_module.html)
  12. Mohan P Edala revised this gist Mar 20, 2019. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -241,7 +241,7 @@
    * Reload the server configuration and try to navigate to the root URL or the status page, we will now see the content.
    * Unfortunately, we appear not to be hitting our HTTP basic authentication anymore.
    * Reason for this is that the $uri is changed before we process the location blocks and we’re never going to have a $uri that matches /admin.html. We need to change that location check to match against /admin instead.
    ```
    ```html highlight="my_highlight"
    server {
    listen 80 default_server;
    listen 443 ssl;
    @@ -258,7 +258,7 @@
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = <b>/admin</b> {
    location = /admin <!-- my_highlight --> {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    @@ -269,6 +269,7 @@
    }
    ```
  13. Mohan P Edala revised this gist Mar 20, 2019. 1 changed file with 275 additions and 227 deletions.
    502 changes: 275 additions & 227 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -1,227 +1,275 @@
    # Genereating a private key and a CSR(Certificate Signing Request )
    Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache HTTP or Nginx web server, and you want to use a Certificate Authority (CA) to issue the SSL certificate. The CSR that is generated can be sent to a CA to request the issuance of a CA-signed SSL certificate. If your CA supports SHA-2, add the -sha256 option to sign the CSR with SHA-2.

    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:

    ```
    openssl req -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr</code></pre>
    ```

    Creating a 2048-bit private key and public key
    ```
    openssl req -x509 -nodes -days 365 \
    -newkey rsa:2048 \
    -keyout /etc/nginx/ssl/private.key \
    -out /etc/nginx/ssl/public.pem
    ```
    Command Explanation:
    ```
    req - We’re making a certificate request to OpenSSL
    -x509 - Specifying the structure that our certificate should have. Conforms to the X.509 standard
    -nodes - Do not encrypt the output key
    -days 365 - Set the key to be valid for 365 days
    -newkey rsa:2048 - Generate an RSA key that is 2048 bits in size
    -keyout /etc/nginx/ssl/private.key - File to write the private key to
    -out /etc/nginx/ssl/public.pem - Output file for public portion of key
    -new option, which is not included here but implied, indicates that a CSR is being generated.
    ```
    After running the above command answer the CSR information
    <pre><code>
    Country Name (2 letter code) [AU]:US
    State or Province Name (full name) [Some-State]:New York
    Locality Name (eg, city) []:Brooklyn
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Brooklyn Company
    Organizational Unit Name (eg, section) []:Technology Division
    Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
    Email Address []:</pre></code>

    Non interactively answer CSR
    <pre><code>-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"</pre></code>

    # Generate a CSR from an Existing Private Key
    This command creates a new CSR (domain.csr) based on an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -out domain.csr</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -key option specifies an existing private key (domain.key) that will be used to generate a new CSR.
    2. -new option indicates that a CSR is being generated.

    # Generate a CSR from an Existing Certificate and Private Key
    This command creates a new CSR (domain.csr) based on an existing certificate (domain.crt) and private key (domain.key):
    <pre><code>openssl x509 -in domain.crt -signkey domain.key -x509toreq -out domain.csr</pre></code>
    The -x509toreq option specifies that you are using an X509 certificate to make a CSR.

    ## Generating SSL Certificates
    # Generate a Self-Signed Certificate
    This command creates a 2048-bit private key (domain.key) and a self-signed certificate (domain.crt) from scratch:
    <pre><code>openssl req -newkey rsa:2048 -nodes -keyout domain.key -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -x509 option tells req to create a self-signed cerificate.
    2. -days 365 option specifies that the certificate will be valid for 365 days. A temporary CSR is generated to gather information to associate with the certificate.

    # Generate a Self-Signed Certificate from an Existing Private Key
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.
    1. -x509 option tells req to create a self-signed cerificate.
    2. 365 option specifies that the certificate will be valid for 365 days.
    3. -new option enables the CSR information prompt.

    # Generate a Self-Signed Certificate from an Existing Private Key and CSR
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key) and (domain.csr):
    <pre><code>openssl x509 -signkey domain.key -in domain.csr -req -days 365 -out domain.crt</pre></code>

    # View Certificates
    Certificate and CSR files are encoded in PEM format, which is not readily human-readable.

    This section covers OpenSSL commands that will output the actual entries of PEM-encoded files.

    # View CSR Entries
    This command allows you to view and verify the contents of a CSR (domain.csr) in plain text:
    <pre><code>openssl req -text -noout -verify -in domain.csr</pre></code>
    # View Certificate Entries
    This command allows you to view the contents of a certificate (domain.crt) in plain text:
    <pre><code>openssl x509 -text -noout -in domain.crt</pre></code>
    # Verify a Certificate was Signed by a CA
    Use this command to verify that a certificate (domain.crt) was signed by a specific CA certificate (ca.crt):
    <pre><code>openssl verify -verbose -CAFile ca.crt domain.crt</pre></code>
    ## Private Keys
    This section covers OpenSSL commands that are specific to creating and verifying private keys.
    # Create a Private Key
    Use this command to create a password-protected, 2048-bit private key (domain.key):
    <pre><code>openssl genrsa -des3 -out domain.key 2048</pre></code>
    Enter a password when prompted to complete the process.

    # Verify a Private Key
    Use this command to check that a private key (domain.key) is a valid key:
    <pre><code>openssl rsa -check -in domain.key</pre></code>
    If your private key is encrypted, you will be prompted for its pass phrase. Upon success, the unencrypted key will be output on the terminal.

    # Verify a Private Key Matches a Certificate and CSR
    Use these commands to verify if a private key (domain.key) matches a certificate (domain.crt) and CSR (domain.csr):
    <pre><code>
    openssl rsa -noout -modulus -in domain.key | openssl md5
    openssl x509 -noout -modulus -in domain.crt | openssl md5
    openssl req -noout -modulus -in domain.csr | openssl md5
    </pre></code>
    If the output of each command is identical there is an extremely high probability that the private key, certificate, and CSR are related.

    # Encrypt a Private Key
    This takes an unencrypted private key (unencrypted.key) and outputs an encrypted version of it (encrypted.key):
    <pre><code>
    openssl rsa -des3 -in unencrypted.key -out encrypted.key</pre></code>
    Enter your desired pass phrase, to encrypt the private key with.
    # Decrypt a Private Key
    This takes an encrypted private key (encrypted.key) and outputs a decrypted version of it (decrypted.key):
    <pre><code>openssl rsa -in encrypted.key -out decrypted.key</pre></code>
    Enter the pass phrase for the encrypted key when prompted.

    Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)

    -----------------------------------------------------------------
    * To Show the certificate

    openssl s_client -connect example.com:443


    * Import a certificate
    ```
    openssl s_client -connect example.com:443 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > example.com.crt
    ```
    * If you face any issue (Ex: -bash: /dev/null : No such file or directory) try it in the below way

    1. Import the certificate
    ```
    openssl s_client -connect example.com:443 > example.com.txt
    ```
    2. Check if the certificate is present or not
    ```
    cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
    ```
    3. Copy the certificate part to a .crt file
    ```
    cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee example.crt
    ```
    4. verify it
    ```
    cat example.com.crt
    ```
    5. Change the password of a pfx file

    - Export you current certificate to a passwordless pem type
    ```
    openssl pkcs12 -in example.com.pfx -out example.com.pem -nodes
    ```
    - Convert the passwordless pem to a new pfx file with password:
    ```
    openssl pkcs12 -export -name example.com.pfx -out example.com.pfx -in example.com.pem
    ```
    --------------------------------------------------------------

    ### Java keytool

    #### TrustStore vs keyStore:
    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

    [Reference click here](http://www.java67.com/2012/12/difference-between-truststore-vs.html)

    ##### Starting the application server with the keystores
    ```
    -Djavax.net.ssl.keyStore=%CLIENT_CERT%
    -Djavax.net.ssl.keyStorePassword=endeca
    -Djavax.net.ssl.trustStore=%CLIENT_CERT%
    -Djavax.net.ssl.trustStorePassword=endeca
    ```

    #### Create a Truststore

    ```
    keytool -import -alias alias-ofthe-cert -file cert-name.com.cer -storetype JKS -keystore testTruststore
    ```
    #### Update keystore with a certificate

    ```
    keytool -import -file <cert_name>.cer -alias <alias_name_to_identify_inside_truststore.github.com> -keystore <trustorefile_name>
    ```
    #### Delete keystore cert
    ```
    keytool -delete -alias <alias_name_of_the_cert_in_keystore.github.com> -keystore <keystore_name>
    ```
    #### List keystore
    ```
    keytool -list -v -keystore <keystore_name>
    ```
    #### Delete a certificate from a Java Keytool keystore
    ```
    keytool -delete -alias mydomain -keystore keystore.jks
    ```
    #### Change a Java keystore password
    ```
    keytool -storepasswd -new new_storepass -keystore keystore.jks
    ```
    #### Export a certificate from a keystore
    ```
    keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
    ```
    #### Check a stand-alone certificate
    ```
    keytool -printcert -v -file mydomain.crt
    ```
    #### Generate a Java keystore and key pair
    ```
    keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
    ```
    ##### Options
    ```
    -storepass xxxxxx
    ```
    ##### Check Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt
    ```
    ##### Extract only the Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt | grep "Signature Algorithm" | uniq
    ```
    ### Virtual Host and Serving Static Content

    * Default path: vim /etc/nginx/conf.d/default.conf
    * Custom Config vim /etc/nginx/conf.d/example.com.conf

    * Default index.html: /usr/share/nginx/html/index.html
    * Custom index.html: /var/www/example.com/html/index.html
    - Path explanation:
    - Default path : /var/www/
    - Virtualhostname : example.com

    * Test Configuration of the server
    ```
    nginx -t
    ```
    * Test Ouput:
    ```
    curl localhost
    ```
    * Test Configuration of a different hosts/virtualservers
    ```
    curl --header "Host: example.com" localhost
    ```
    * Troubleshooting:
    - Error 403:
    ```
    [root@dimpastra1 nginx]# curl --header "Host: example.com" localhost
    <html>
    <head><title>403 Forbidden</title></head>
    <body bgcolor="white">
    <center><h1>403 Forbidden</h1></center>
    <hr><center>nginx/1.14.2</center>
    </body>
    </html>
    ```
    - Solution: Check the error logs
    - Reason is due to selinux security
    ```
    less /var/log/nginx/error.log
    2019/03/19 21:30:49 [error] 30362#30362: *13 "/var/www/example.com/html/index.html" is forbidden (13: Permission denied), client: 127.0.0.1, server: example.com, request: "GET / HTTP/1.1", host: "example.com"
    ```
    * Check if proper permission exsists to display the content
    ```
    semanage fcontext -l | grep /usr/share/nginx/html
    semanage fcontext -a -t httpd_sys_content_t '/var/www/(/.*)?'
    semanage fcontext -l | grep /var/www
    ```
    * To get the proper permissions to use the virtulhosts
    ```
    restorecon -R -v /var/www
    ```
    ### Error pages for Default Hosts
    * To add error messages
    ```
    vim /etc/nginx/conf.d/default.conf
    ```
    ```
    server {
    listen 80 default_server;
    server_name _;
    root /usr/share/nginx/html;
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Create html pages for errors at the below location
    ```
    vim /usr/share/nginx/html/404.html
    ```
    ### Access Control with HTTP Basic Auth
    * HTTP basic authentication allows us to require a username and password before we allow a user to access a specific URL. To set up NGINX with HTTP basic auth, we’ll be using the auth_basic module. We can specify that specific location blocks utilize basic auth while others do not. Let’s create a new location block that will prevent a specific HTML file from being accessible:
    ```
    vim etc/nginx/conf.d/default.conf
    ```
    ```
    server {
    listen 80 default_server;
    server_name _;
    root /usr/share/nginx/html;
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * The location = /admin.html is how we specify what should happen if someone navigates to the /admin.html path and it matches exactly. From there, we’re able to specify a value for auth_basic using a string (any string will do), and we give the path to the file containing the username/password pairs that have access.
    * Create the admin.html
    ```
    [root] $ echo "<h1>Admin Page</h1>" > /usr/share/nginx/html/admin.html
    ```
    * Generating a Password File
    - Our configuration is currently valid, but we don’t have a password file to work with yet. We’re going to install the httpd-tools to create our .htpasswd file:
    ```
    yum install -y httpd-tools
    ```
    * now have access to the htpasswd utility that can generate a file for us with encrypted passwords for our users
    ```
    [root] $ htpasswd -c /etc/nginx/.htpasswd admin
    New password:
    Re-type new password:
    Adding password for user admin
    ```
    * Test the configuration
    ```
    systemctl reload nginx
    [root@dimpastra1 nginx]# curl localhost/admin.html
    <html>
    <head><title>401 Authorization Required</title></head>
    <body bgcolor="white">
    <center><h1>401 Authorization Required</h1></center>
    <hr><center>nginx/1.14.2</center>
    </body>
    </html>
    ```
    * se the -u flag for curl, then we can pass in the username and password divided by a
    ```
    [root@dimpastra1 nginx]# curl -u admin:****** localhost/admin.html
    <h1>ADMIN PAGE</h1>
    ```
    ### NGINX Security
    * Create SSL certificate using [openssl](https://gist.github.com/mohanpedala/468cf9cef473a8d7610320cff730cdd1)
    * Configuring the Host for SSL/TLS/HTTPS using Nginx http module, server directive, ssl module.
    * Configure https server
    ```
    server {
    listen 80 default_server;
    <b> listen 443 ssl; </b>
    server_name _;
    root /usr/share/nginx/html;
    <b> ssl_certificate /etc/nginx/ssl/public.pem; </b>
    <b> ssl_certificate_key /etc/nginx/ssl/private.key;</b>
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Test connection
    ```
    curl -k https://localhost
    ```
    ### Rewrite rules (Cleaning Up URLs)
    * Documentation
    - NGINX http module
    - NGINX server directive
    - NGINX try_files directive
    - NGINX rewrite directive
    * Remove .html at the end of our files. To remove this, we’re going to utilize the rewrite and try_files directives.
    * Convert URLs using a rewrite rule. Going to /admin.html should redirect to /admin.
    * Use try_files to ensure that we're rendering the proper page or rendering a 404.
    ```
    vim /etc/nginx/conf.d/default.conf
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    <b> rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;</b>
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    * Rewrite rules follow the regex pattern.
    ```
    rewrite REGEX REPLACEMENT [flag];
    ```
    * Regex break down
    ```
    ^(/.*)\.html(\?.*)?$
    ```
    - The starting ```^``` indicates that we’re going from the very beginning of the URI. We create a capture group using parentheses.
    - The pattern ```/.*``` means starting with a ```/``` and including all characters after that.
    - Next, we expect to find a ```.html``` (notices that we needed to escape it using a ```)```.
    - Lastly, we create another capture group that gets an optional query string (anything after a ?) until the end of the URI (as indicated by the $ character).
    - The capture groups will be usable in the REPLACEMENT portion of the direction using ```$1, $2, etc```.
    * Reload the server
    ```
    systemctl reload nginx
    ```
    * Test it by opening a browser and hit the nginx server public ip.
    * we’ll run into an infinite redirect loop. This is happening because we’re even reloading the 404.html page so we can’t even render that properly. To fix this redirect loop, we’ll need to use try_files.
    ```
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    <b>location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }</b>
    location = /admin.html {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    <b> try_files $uri/index.html $uri.html $uri/ $uri =404;</b>
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    Explanation:
    - We’ve added a try_files directive to both of our location blocks with slightly different rules. We want to be able to handle someone going to the index.html within potentially nested directories.
    - The try_files call will look for the first file (or directory) that matches the request moving from left to right. If nothing is found, then the rightmost file or status code will be returned.
    * Reload the server configuration and try to navigate to the root URL or the status page, we will now see the content.
    * Unfortunately, we appear not to be hitting our HTTP basic authentication anymore.
    * Reason for this is that the $uri is changed before we process the location blocks and we’re never going to have a $uri that matches /admin.html. We need to change that location check to match against /admin instead.
    ```
    server {
    listen 80 default_server;
    listen 443 ssl;
    server_name _;
    root /usr/share/nginx/html;
    ssl_certificate /etc/nginx/ssl/public.pem;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    rewrite ^(/.*)\.html(\?.*)?$ $1$2 redirect;
    rewrite ^/(.*)/$ /$1 redirect;
    location / {
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    location = <b>/admin</b> {
    auth_basic "Login Required";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri/index.html $uri.html $uri/ $uri =404;
    }
    error_page 404 /404.html;
    error_page 500 501 502 503 504 /50x.html;
    }
    ```
    [For Syntax Reference](http://nginx.org/en/docs/http/ngx_http_core_module.html)
  14. Mohan P Edala revised this gist Mar 20, 2019. 1 changed file with 20 additions and 5 deletions.
    25 changes: 20 additions & 5 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -3,13 +3,28 @@ Use this method if you want to use HTTPS (HTTP over TLS) to secure your Apache H

    Creating a 2048-bit private key (domain.key) and a CSR (domain.csr) from scratch:

    <pre><code>openssl req -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr</code></pre>
    ```
    openssl req -newkey rsa:2048 -nodes -keyout domain.key -out domain.csr</code></pre>
    ```

    Creating a 2048-bit private key and public key
    ```
    openssl req -x509 -nodes -days 365 \
    -newkey rsa:2048 \
    -keyout /etc/nginx/ssl/private.key \
    -out /etc/nginx/ssl/public.pem
    ```
    Command Explanation:
    1. -newkey rsa: 2048 option specifies that the key should be 2048-bit, generated using the RSA algorithm.
    2. -nodes option specifies that the private key should not be encrypted with a pass phrase.
    3. -new option, which is not included here but implied, indicates that a CSR is being generated.

    ```
    req - We’re making a certificate request to OpenSSL
    -x509 - Specifying the structure that our certificate should have. Conforms to the X.509 standard
    -nodes - Do not encrypt the output key
    -days 365 - Set the key to be valid for 365 days
    -newkey rsa:2048 - Generate an RSA key that is 2048 bits in size
    -keyout /etc/nginx/ssl/private.key - File to write the private key to
    -out /etc/nginx/ssl/public.pem - Output file for public portion of key
    -new option, which is not included here but implied, indicates that a CSR is being generated.
    ```
    After running the above command answer the CSR information
    <pre><code>
    Country Name (2 letter code) [AU]:US
  15. Mohan P Edala revised this gist Mar 7, 2019. 1 changed file with 9 additions and 1 deletion.
    10 changes: 9 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -201,4 +201,12 @@ keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
    ##### Options
    ```
    -storepass xxxxxx
    ```
    ```
    ##### Check Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt
    ```
    ##### Extract only the Hashing Algorithm
    ```
    openssl x509 -noout -text -in example.crt | grep "Signature Algorithm" | uniq
    ```
  16. phaneindra revised this gist Aug 22, 2018. 1 changed file with 9 additions and 0 deletions.
    9 changes: 9 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -133,7 +133,16 @@ cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee
    ```
    cat example.com.crt
    ```
    5. Change the password of a pfx file

    - Export you current certificate to a passwordless pem type
    ```
    openssl pkcs12 -in example.com.pfx -out example.com.pem -nodes
    ```
    - Convert the passwordless pem to a new pfx file with password:
    ```
    openssl pkcs12 -export -name example.com.pfx -out example.com.pfx -in example.com.pem
    ```
    --------------------------------------------------------------

    ### Java keytool
  17. phaneindra revised this gist Aug 7, 2018. 1 changed file with 8 additions and 0 deletions.
    8 changes: 8 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -142,6 +142,14 @@ cat example.com.crt
    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

    [Reference click here](http://www.java67.com/2012/12/difference-between-truststore-vs.html)

    ##### Starting the application server with the keystores
    ```
    -Djavax.net.ssl.keyStore=%CLIENT_CERT%
    -Djavax.net.ssl.keyStorePassword=endeca
    -Djavax.net.ssl.trustStore=%CLIENT_CERT%
    -Djavax.net.ssl.trustStorePassword=endeca
    ```

    #### Create a Truststore

  18. phaneindra revised this gist Aug 1, 2018. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -140,6 +140,8 @@ cat example.com.crt

    #### TrustStore vs keyStore:
    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

    [Reference click here](http://www.java67.com/2012/12/difference-between-truststore-vs.html)

    #### Create a Truststore

  19. phaneindra revised this gist Aug 1, 2018. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -138,7 +138,8 @@ cat example.com.crt

    ### Java keytool

    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.
    #### TrustStore vs keyStore:
    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

    #### Create a Truststore

  20. phaneindra revised this gist Aug 1, 2018. 1 changed file with 7 additions and 0 deletions.
    7 changes: 7 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -138,6 +138,13 @@ cat example.com.crt

    ### Java keytool

    Main difference between trustStore vs keyStore is that trustStore (as name suggest) is used to store certificates from trusted Certificate authorities(CA) which are used to verify certificate presented by Server in SSL Connection while keyStore is used to store private key and own identity certificate which program should present to other parties (Server or client) to verify its identity. That was one liner difference between trustStore vs keyStore in Java but no doubt these two terms are quite a confusion not just for anyone who is the first time doing SSL connection in Java but also many intermediate and senior level programmer. One reason of this could be SSL setup being a one-time job and not many programmers get opportunity to do that. In this Java article, we will explore both keystore and trust stores and understand key differences between them. By the way, you can use a keytool command to view certificates from truststore and keystore. keytool command comes with Java installation and its available in the bin directory of JAVA_HOME.

    #### Create a Truststore

    ```
    keytool -import -alias alias-ofthe-cert -file cert-name.com.cer -storetype JKS -keystore testTruststore
    ```
    #### Update keystore with a certificate

    ```
  21. phaneindra revised this gist Mar 29, 2018. 1 changed file with 5 additions and 1 deletion.
    6 changes: 5 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -170,4 +170,8 @@ keytool -printcert -v -file mydomain.crt
    #### Generate a Java keystore and key pair
    ```
    keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
    ```
    ```
    ##### Options
    ```
    -storepass xxxxxx
    ```
  22. phaneindra revised this gist Mar 16, 2018. 1 changed file with 20 additions and 0 deletions.
    20 changes: 20 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -150,4 +150,24 @@ keytool -delete -alias <alias_name_of_the_cert_in_keystore.github.com> -keystore
    #### List keystore
    ```
    keytool -list -v -keystore <keystore_name>
    ```
    #### Delete a certificate from a Java Keytool keystore
    ```
    keytool -delete -alias mydomain -keystore keystore.jks
    ```
    #### Change a Java keystore password
    ```
    keytool -storepasswd -new new_storepass -keystore keystore.jks
    ```
    #### Export a certificate from a keystore
    ```
    keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks
    ```
    #### Check a stand-alone certificate
    ```
    keytool -printcert -v -file mydomain.crt
    ```
    #### Generate a Java keystore and key pair
    ```
    keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -keysize 2048
    ```
  23. phaneindra revised this gist Mar 10, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -150,4 +150,4 @@ keytool -delete -alias <alias_name_of_the_cert_in_keystore.github.com> -keystore
    #### List keystore
    ```
    keytool -list -v -keystore <keystore_name>
    ``
    ```
  24. phaneindra revised this gist Mar 10, 2018. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -134,6 +134,9 @@ cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee
    cat example.com.crt
    ```

    --------------------------------------------------------------

    ### Java keytool

    #### Update keystore with a certificate

  25. phaneindra revised this gist Mar 10, 2018. 1 changed file with 46 additions and 1 deletion.
    47 changes: 46 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -102,4 +102,49 @@ This takes an encrypted private key (encrypted.key) and outputs a decrypted vers
    <pre><code>openssl rsa -in encrypted.key -out decrypted.key</pre></code>
    Enter the pass phrase for the encrypted key when prompted.

    Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
    Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)

    -----------------------------------------------------------------
    * To Show the certificate

    openssl s_client -connect example.com:443


    * Import a certificate
    ```
    openssl s_client -connect example.com:443 < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > example.com.crt
    ```
    * If you face any issue (Ex: -bash: /dev/null : No such file or directory) try it in the below way

    1. Import the certificate
    ```
    openssl s_client -connect example.com:443 > example.com.txt
    ```
    2. Check if the certificate is present or not
    ```
    cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
    ```
    3. Copy the certificate part to a .crt file
    ```
    cat example.com.txt | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee example.crt
    ```
    4. verify it
    ```
    cat example.com.crt
    ```


    #### Update keystore with a certificate

    ```
    keytool -import -file <cert_name>.cer -alias <alias_name_to_identify_inside_truststore.github.com> -keystore <trustorefile_name>
    ```
    #### Delete keystore cert
    ```
    keytool -delete -alias <alias_name_of_the_cert_in_keystore.github.com> -keystore <keystore_name>
    ```
    #### List keystore
    ```
    keytool -list -v -keystore <keystore_name>
    ``
  26. phaneindranath revised this gist Jul 20, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -102,4 +102,4 @@ This takes an encrypted private key (encrypted.key) and outputs a decrypted vers
    <pre><code>openssl rsa -in encrypted.key -out decrypted.key</pre></code>
    Enter the pass phrase for the encrypted key when prompted.

    # Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
    Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
  27. phaneindranath revised this gist Jul 20, 2017. 1 changed file with 47 additions and 0 deletions.
    47 changes: 47 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -56,3 +56,50 @@ Answer the CSR information prompt to complete the process.
    # Generate a Self-Signed Certificate from an Existing Private Key and CSR
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key) and (domain.csr):
    <pre><code>openssl x509 -signkey domain.key -in domain.csr -req -days 365 -out domain.crt</pre></code>

    # View Certificates
    Certificate and CSR files are encoded in PEM format, which is not readily human-readable.

    This section covers OpenSSL commands that will output the actual entries of PEM-encoded files.

    # View CSR Entries
    This command allows you to view and verify the contents of a CSR (domain.csr) in plain text:
    <pre><code>openssl req -text -noout -verify -in domain.csr</pre></code>
    # View Certificate Entries
    This command allows you to view the contents of a certificate (domain.crt) in plain text:
    <pre><code>openssl x509 -text -noout -in domain.crt</pre></code>
    # Verify a Certificate was Signed by a CA
    Use this command to verify that a certificate (domain.crt) was signed by a specific CA certificate (ca.crt):
    <pre><code>openssl verify -verbose -CAFile ca.crt domain.crt</pre></code>
    ## Private Keys
    This section covers OpenSSL commands that are specific to creating and verifying private keys.
    # Create a Private Key
    Use this command to create a password-protected, 2048-bit private key (domain.key):
    <pre><code>openssl genrsa -des3 -out domain.key 2048</pre></code>
    Enter a password when prompted to complete the process.

    # Verify a Private Key
    Use this command to check that a private key (domain.key) is a valid key:
    <pre><code>openssl rsa -check -in domain.key</pre></code>
    If your private key is encrypted, you will be prompted for its pass phrase. Upon success, the unencrypted key will be output on the terminal.

    # Verify a Private Key Matches a Certificate and CSR
    Use these commands to verify if a private key (domain.key) matches a certificate (domain.crt) and CSR (domain.csr):
    <pre><code>
    openssl rsa -noout -modulus -in domain.key | openssl md5
    openssl x509 -noout -modulus -in domain.crt | openssl md5
    openssl req -noout -modulus -in domain.csr | openssl md5
    </pre></code>
    If the output of each command is identical there is an extremely high probability that the private key, certificate, and CSR are related.

    # Encrypt a Private Key
    This takes an unencrypted private key (unencrypted.key) and outputs an encrypted version of it (encrypted.key):
    <pre><code>
    openssl rsa -des3 -in unencrypted.key -out encrypted.key</pre></code>
    Enter your desired pass phrase, to encrypt the private key with.
    # Decrypt a Private Key
    This takes an encrypted private key (encrypted.key) and outputs a decrypted version of it (decrypted.key):
    <pre><code>openssl rsa -in encrypted.key -out decrypted.key</pre></code>
    Enter the pass phrase for the encrypted key when prompted.

    # Reference [link](https://www.digitalocean.com/community/tutorials/openssl-essentials-working-with-ssl-certificates-private-keys-and-csrs)
  28. phaneindranath revised this gist Jul 20, 2017. 1 changed file with 22 additions and 0 deletions.
    22 changes: 22 additions & 0 deletions OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -33,4 +33,26 @@ Answer the CSR information prompt to complete the process.

    # Generate a CSR from an Existing Certificate and Private Key
    This command creates a new CSR (domain.csr) based on an existing certificate (domain.crt) and private key (domain.key):
    <pre><code>openssl x509 -in domain.crt -signkey domain.key -x509toreq -out domain.csr</pre></code>
    The -x509toreq option specifies that you are using an X509 certificate to make a CSR.

    ## Generating SSL Certificates
    # Generate a Self-Signed Certificate
    This command creates a 2048-bit private key (domain.key) and a self-signed certificate (domain.crt) from scratch:
    <pre><code>openssl req -newkey rsa:2048 -nodes -keyout domain.key -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -x509 option tells req to create a self-signed cerificate.
    2. -days 365 option specifies that the certificate will be valid for 365 days. A temporary CSR is generated to gather information to associate with the certificate.

    # Generate a Self-Signed Certificate from an Existing Private Key
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -x509 -days 365 -out domain.crt</pre></code>
    Answer the CSR information prompt to complete the process.
    1. -x509 option tells req to create a self-signed cerificate.
    2. 365 option specifies that the certificate will be valid for 365 days.
    3. -new option enables the CSR information prompt.

    # Generate a Self-Signed Certificate from an Existing Private Key and CSR
    This command creates a self-signed certificate (domain.crt) from an existing private key (domain.key) and (domain.csr):
    <pre><code>openssl x509 -signkey domain.key -in domain.csr -req -days 365 -out domain.crt</pre></code>
  29. phaneindranath revised this gist Jul 20, 2017. 1 changed file with 13 additions and 1 deletion.
    14 changes: 13 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -21,4 +21,16 @@ Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
    Email Address []:</pre></code>

    Non interactively answer CSR
    <pre><code>-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"</pre></code>
    <pre><code>-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"</pre></code>

    # Generate a CSR from an Existing Private Key
    This command creates a new CSR (domain.csr) based on an existing private key (domain.key):
    <pre><code>openssl req -key domain.key -new -out domain.csr</pre></code>
    Answer the CSR information prompt to complete the process.

    1. -key option specifies an existing private key (domain.key) that will be used to generate a new CSR.
    2. -new option indicates that a CSR is being generated.

    # Generate a CSR from an Existing Certificate and Private Key
    This command creates a new CSR (domain.csr) based on an existing certificate (domain.crt) and private key (domain.key):

  30. phaneindranath revised this gist Jul 20, 2017. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion OpenSSL.md
    Original file line number Diff line number Diff line change
    @@ -18,4 +18,7 @@ Locality Name (eg, city) []:Brooklyn
    Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example Brooklyn Company
    Organizational Unit Name (eg, section) []:Technology Division
    Common Name (e.g. server FQDN or YOUR name) []:examplebrooklyn.com
    Email Address []:</pre></code>
    Email Address []:</pre></code>

    Non interactively answer CSR
    <pre><code>-subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=examplebrooklyn.com"</pre></code>