Author: montyvijh

Generating Client/Server Certificates with your own Certification Authority


In some of the previous posts, I gave some overview about SSL and how to configure SSL on a local server. To create a secure channel between two sources using TLS protocol, we need certificates which will have the security algorithm. This post will help you to create the certificates using OpenSSL library. I will try to give brief about each command for better understanding:

Open up your bash/terminal/cmd to run these commands. Also, make sure to create a separate directory structure for certificates.

Generate a CA

openssl req -out ca.pem -new -x509

Description : This command is use to create a self signed certificate which can be used as a local CA.

Note: This command will also create the CA key named as “privkey.pem”.

openssl – This specifies that we are going to use OpenSSL library

req – This refer to the certificate request

-out – This specifies the output filename to write to or use the standard default

-x509 – This option outputs a self-signed certificate.

-new – This option is use to specify that its a new certificate request.

Generate a Server Certificate

openssl genrsa -out server.key 1024

Description : This command is use to generate the RSA key which would form the base algorithm for the Certificate.

genrsa – This command is used to generate RSA private key

1024 – This is the key length (You can use others like 2048, 4096 etc.)

openssl req -key server.key -new -out server.req

Description : This command is used to create a certificate request with embedded key generated in the last step

-key – This specifies the file to read private key.

openssl x509 -req -in server.req -CA CA.pem -CAkey privkey.pem -CAserial -out server.pem

Description: This command is used to sign the server request and create the certificate authorized by local CA.

Note: If you are using OpenSSL certificates for the first time then instead of “CAserial”, you have to use “CAcreateserial” and later you can use the same file created. This serial file is used by CA to keep the index for certificates created.

x509 – The x509 command is a multi purpose certificate utility. It can be used to display certificate information, convert certificates to various forms, sign certificate requests like a “mini CA” or edit certificate trust settings.

-req – by default, a certificate is expected on input. With this option, a certificate request is expected instead.

-CA – This is used to specify the CA certificate to be used.

-CAkey – This is used to specify the CA key to be used.

-CAserial – This is used to specify the serial file to be used.

Generate a Client Certificate

openssl genrsa -out client.key 1024

Description: This command is similar to what we did in server key generation

openssl req -key client.key -new -out client.req

Description: This command is similar to what we did for creating the server certificate request.

openssl x509 -req -in client.req -CA CA.pem -CAkey privkey.pem -CAserial -out client.pem

Description: This command is similar to what we did for creating the server certificate.

We are done with creating the certificates. Now you can import the certificates to your server and client to setup a secure channel. In later posts, I would give more about the commands in OpenSSL. You can follow up on this link to check the common commands used: OpenSSL Common Commands


Getting started with Cryptography Library

There are many cryptography libraries available for use and my suggestion is when you are implementing a cryptography algorithm then don’t do it by yourself, instead use one of these libraries like OpenSSL, WolfSSL, PolarSSL etc.

The code which I am going to share would mostly build upon OpenSSL.

Why OpenSSL?

OpenSSL is a general purpose cryptography library that provides open source implementation of Secure Sockets Layer (SSL) and Transport Layer Security (TLS) protocols.

This library includes a wide variety of cryptography algorithms like RSA, ECC and Certificate signing requests, checksums, managing certificates and performing encryption/decryption. The library is written in C language but it also has wrappers available for many other languages.

The Mac Operating System already comes with an installation of OpenSSL, which you can upgrade by using HomeBrew or Ports but for the coding purpose, you can follow this link to compile and install OpenSSL:

If you are working on Windows, then you can follow this link to compile and install OpenSSL:

After you configure and build the library, you should always perform a make test to ensure the library performs as expected under its self-tests.

RSA (cryptosystem) – Part 3 (Encryption and Decryption)

This is the process of transforming a plaintext message into ciphertext, or vice-versa. The RSA function, for message m and key k is evaluated as follows:


There are two cases:

  1. Encrypting with the public key, and then decrypting with the private key.
  2. Encrypting with the private key, and then decrypting with the public key.

The two cases above are mirrors. I will explain the first case, the second follows from the first

Encryption: F(m,e)=memodn=c, where m is the message, e is the public key and c is the cipher.

Decryption: F(c,d)=cdmodn=m, where m is the message, d is the private key and c is the cipher.


Following the example from the previous post:

  1. We choose two distinct prime numbers, such asp=61 and  q=53
  2. Compute n = pq giving n=61.53=3233
  3. Compute the totient of the product as ϕ(n) = lcm(p − 1, q − 1) giving ϕ(3233)= lcm(60,52)=780
  4. Choose any number 1 < e < 780 that is coprime to 780. Choosing a prime number for e leaves us only to check that e is not a divisor of 780.Let e=17
  5. Compute d, the modular multiplicative inverse of e (mod ϕ(n)) yielding,d=413

The public key is (n = 3233, e = 17). For a padded plaintext message m, the encryption function is

c(m) = m17 mod 3233

The private key is (n = 3233, d = 413). For an encrypted ciphertext c, the decryption function is

m(c) = c413 mod 3233

For instance, in order to encrypt m = 65, we calculate

c = 6517 mod 3233 =2790

To decrypt c = 2790, we calculate

m = 2790413 mod 3233 = 65

Please note the whole security of RSA system depends on the selection of p and q for the algorithm. A real world example for p and q could be:



and as per the algorithm, you can calculate other parameters.

RSA is very helpful in building secure products and I hope you understood the basic concept of RSA with these posts:

RSA – Part 1

RSA – Part 2

RSA – Part 3


RSA (cryptosystem) – Part 2 (Key Generation Algorithm)

The mathematics described in the previous post is enough to describe RSA and show how it works. RSA is actually a set of two algorithms:

  1. Key Generation: A key generation algorithm.
  2. RSA Function Evaluation: A function F, that takes as input a point x and a key k and produces either an encrypted result or plain text, depending on the input and the key.

Key Generation

The key generation algorithm is the most complex part of RSA. The aim of the key generation algorithm is to generate both the public and the private RSA keys.This has to be done correctly in order to generate secure RSA keys, else it opens up the system for many different attacks (We will talk about the attacks later). I will break down the steps involved to generate keys with the mathematics functions used within that:

  1. Large Prime Number Generation: Two large prime numbers p and q need to be generated. These numbers are very large up to 1024 digits or even 2048 digits. For security purposes, the integers p and q should be chosen at random, and should be similar in magnitude but differ in length by a few digits to make factoring harder.
  2. Modulus: From the two large numbers, a modulus n is generated by multiplying p and q.
  3. Totient: The totient of n, ϕ(n)is calculated.
  4. Public Key: A prime number is calculated from the range [1 , ϕ(n)] that has a greatest common divisor of 1 with ϕ(n).
  5. Private Key: Because the prime in step 4 has a gcd of 1 with ϕ(n), we are able to determine its inverse with respect to modϕ(n).

Let’s see how each step works with an example:

Large Prime Number Generation

RSA security depends on two very large prime numbers that are quite far apart. Generating composite numbers, or even prime numbers that are close together makes RSA totally insecure.

So how to generate large prime numbers? The answer is to pick a large random number and test for primness. If that number fails the prime test, then add 1 and start over again until we have a number that passes a prime test. For testing a big prime number we have many online/offline tools available which are also known as primality test (Example: Rabin-Miller primality test etc.).

Example: In this post, I am not going to show an example with 2 very large prime numbers. For ease of understanding, lets take two prime numbers as:

p=61 and q=53


Once we have our two prime numbers, we can generate a modulus very easily:


RSA’s main security foundation relies upon the fact that given two large prime numbers, a composite number (in this case n) can very easily be deduced by multiplying the two primes together. But, given just n, there is no known algorithm to efficiently determining n’s prime factors. It is considered a hard problem, many people throughout history had tried and failed to find the solution of this problem.

Example: Compute n = pq giving

n = 61 x 53 = 3233


With the prime factors of n, the totient can be very quickly calculated:



I talked about Totient in the last post. The reason why the RSA becomes vulnerable if one can determine the prime factors of the modulus is because then one can easily determine the totient.

Example: The actual totient calculation is done by taking in LCM but sometimes we may even use just multiplication of (p-1).(q-1) as per our prime numbers but with large prime numbers taking LCM would be much better.

ϕ(n)= LCM(61-1).(53-1) = 780

Public Key

The public key, normally expressed as e, it is a prime number chosen in the range [1,ϕ(n)]. You may think that 1 is a little small, and yes, I agree, if any small number is chosen, it could lead to security flaws. So in practice, the public key is normally set at 65537. Note that because the public key is prime, it has a high chance of a gcd equal to 1 with ϕ(n). If this is not the case, then we must use another prime number.

An interesting observation: If in practice, the number above is set at 65537, then it is not picked at random; surely this is a problem? Actually, no, it isn’t. As the name implies, this key is public and therefore is shared with everyone. As long as the private key cannot be deduced from the public key, we are secure. The reason why the public key is not randomly chosen in practice is because it is desirable not to have a large number. This is because it is more efficient to encrypt with smaller numbers than larger numbers.

The public key is actually a key pair of the exponent e and the modulus n and is present as follows


Example: Choose any number 1 < e < 780 that is coprime to 780. Choosing a prime number for e leaves us only to check that e is not a divisor of 780.

Let e= 17

Then our public key pair is (17,3233)

Private Key

The public key has a gcd of 1 with ϕ(n), the multiplicative inverse of the public key with respect to ϕ(n) can be efficiently and quickly determined using the Extended Euclidean Algorithm. This multiplicative inverse is the private key(d). So , we have the following equation (one of the most important equations in RSA):


Just like the public key, the private key is also a key pair of the exponent d and modulus n:


One of the absolute fundamental security assumptions behind RSA is that given a public key, one cannot efficiently determine the private key.

Example: Compute d, the modular multiplicative inverse of e (mod λ(n)) :


d = 413

So the private key pair is (413, 3233)

In the next post, I will give a brief about RSA Function Evaluation and a big example to showcase how RSA works.



RSA (cryptosystem) – Part 1 (Simple mathematics)

In this post, I am going to explain exactly how RSA public key encryption works. Before start coding and using the Secure Socket Layer we need to understand the base algorithm on which it works and RSA is one of the popular algorithm under its wing. Everything in this post (including this one) are very mathematical, I am going to try and make this break down in some important concepts and make it simple with examples.

I would suggest not the use any of the example in the real world scenario as this algorithm requires to work with a secure padding structure.

Background Mathematics – The thing which makes wonders

Set Of Integers : Modulo P


This is called the set of integers modulo p (or mod p for short). It is a set that contains Integers from 0 up until p−1.

Example: Z10={0,1,2,3,4,5,6,7,8,9}

Remainder After Division

This concept mostly we have all learnt in School, as for example if we divide 7 by 2, we get remainder as 1. This is stated without any notion of real numbers, only integers. This type of math is really vital to RSA, and is one of the reasons that secures RSA. A formal way of stating a remainder after dividing by another number is an equivalence relationship:

x,y,z,k∈Z, x≡ymodz ⟺ x=k⋅z+y

This equation states that if x is equivalent to the remainder (in this case y) after dividing by an integer (in this case z), then x can be written like so: x=k⋅z+y where k is an integer.

Example: Let’s take y =7 and z=5, then the following values of x will hold for the equation:  x=7,x=12,x=17,…. There are all sought of possibilities to get the value of if we keep on changing the value of k. Therefore, x can be written like so: x =k⋅5+7, where k can be any of the infinite amount of integers.

There are two important things to note:

  1. The remainder stays constant always.
  2. As we stated earlier, y∈Z(y is in the set of integers modulo z)

Greatest Common Divisor and Multiplicative Inverse

A multiplicative inverse for x is a number that when multiplied by x, will be equal to 1. The multiplicative inverse of x is written as x−1 and is defined as so:


The greatest common divisor (gcd) between two numbers is the largest integer that will divide both numbers. For example, gcd(3,8)=2.

The interesting thing is that if two numbers have a gcd of 1, then the smaller of the two numbers has a multiplicative inverse in the modulo of the larger number. It is expressed in the following equation:


The above just says that an inverse only exists if the greatest common divisor is 1.

Example: Lets work in the set Z11, then 3∈Z11 and gcd(3,11)=1. Therefore 3 has a multiplicative inverse (written 3−1) in mod11, which is 4. And indeed, 4⋅3=12=1mod11. But not all numbers have inverses. For instance, 3∈Z9 but 3−1does not exist! This is because gcd(3,9)=3≠1.

Let me just give a more detailed version of how this works:

Consider the modular multiplicative inverse of 3 modulo 11, call it x. In order for x to exist it must be that 3 and 11 are co-prime, which is true.


This is equivalent to the computation of finding x such that

3.x = 1.mod11

By observation the one positive value of x that satisfies this equation is is 4 since


As 12 divided by 11 will give you remainder as 1 and thus the equation can be written as above.

Prime Numbers

Prime numbers are very important to the RSA algorithm. A prime is a number that can only be divided without a remainder by itself and 1. For example, 7 is a prime number (any other number besides 1 and 7 will result in a remainder after division) while 10 is not a prime.

This has an important implication: For any prime number p, every number from 1 up to p−1 has a gcd of 1 with p, and therefore has a multiplicative inverse in modulo p.

Euler’s Totient

Euler’s Totient is the number of elements that have a multiplicative inverse in a set of modulo integers. The totient is denoted using the Greek symbol phi (ϕ). The totient is just the count of the number of elements that have their gcd with the modulus equal to 1. This brings us to an important equation regarding the totient and prime numbers:

p∈P, ϕ(p)=p−1

Example: ϕ(9)=|{1,2,4,5,7,8}|=6

As gcd(9,3) =3, gcd(9,6)=3 and gcd(9,9)=9. So only 6 values with which 9 has greatest common divisor as 1.

With the above background, we have enough tools to describe RSA and in the next post we will see, How the RSA algorithm works.


Starting up a local SSL Server

I gave a brief about things to know on Secure Socket Layer(SSL) in my last post. This post is related to setting up a local SSL server for development or testing. This will also get you started with OpenSSL, which is a secure software library.

Now we know that we need a Certificate to setup a secure channel and this certificate should have a public key cryptosystem. Mac OS, already comes with the installation of OpenSSL and for windows you can download from this source :

If required you can upgrade the OpenSSL Library using Homebrew or Ports.

We can either use a certificate generated by a secure Certificate Authority or we can generate our own using SSL for testing. Create a new directory to store the output and navigate to the directory using terminal or cmd. This command will generate a self signed certificate:

openssl req \
-newkey rsa:2048 -nodes -keyout ssl.key \
-x509 -days 365 -out ssl.crt

Public Key Cryptography Standards#10 certificate request and certificate generating utility.

This option outputs a self signed certificate instead of a certificate request. This is typically used to generate a test certificate or a self signed root CA.

-newkey arg
This option creates a new certificate request and a new private key. The argument takes one of several forms. rsa:nbits, where nbits is the number of bits, generates an RSA key nbits in size. (Bigger the size of the key, slower will be the algorithm, In this case I am using 2048 bits, you can also use 4096 bits)

-keyout filename
This gives the filename to write the newly created private key.

-out filename
This specifies the output filename to write to or standard output by default.

-days XXX
When the -x509 option is being used this specifies the number of days to certify the certificate i.e the validity(The default is 30 days and I am using 365)

If this option is specified then if a private key is created it will not be encrypted.

Enabling SSL in Apache Server

The mac operating system comes with installation of Apache Server. On windows you install Apache Server. Now to setup the SSL , We need to modify httpd.conf located at:


To modify the httpd.conf file we will use nano text editor. You might need to give root permissions to the commands, so just add “sudo” in front of them.

$ cd /etc/apache2/
$ sudo nano httpd.conf

Find the following lines and uncomment it. Just in case you are not sure, comments have a leading pound/hash symbol ( # ) – just remove it.

LoadModule ssl_module libexec/apache2/
Include /private/etc/apache2/extra/httpd-ssl.conf

Save the file using ctrl+X and type ‘yes’ and press return.

The last step is to configure httpd-ssl.conf which is located at:
To modify the httpd-ssl.conf file we will again use nano text editor.

$ cd /etc/apache2/extra
$ sudo nano httpd-ssl.conf

Add the following NameVirtualHost directive :

NameVirtualHost *:443
Listen 443

You can specify your own port number. The default is 443
Also configure your default virtualhost :

DocumentRoot "/Users/mayank/Sites"
ServerName localhost:443
SSLEngine on
SSLProtocol all -SSLv2
SSLCertificateFile "/private/etc/apache2/ssl/ssl.crt"
SSLCertificateKeyFile "/private/etc/apache2/ssl/ssl.key"

You can either copy the cert and key to the directory or specify your own directory for Certificate file and Key file.

Additional Virtual Host setup (not required for test server):
To setup a new virtualhost, enable ssl in your vhost directive :
DocumentRoot “/Users/charles/Sites/project
Options FollowSymLinks Indexes
AllowOverride All
SSLEngine on
SSLProtocol all -SSLv2
SSLCertificateFile “/private/etc/apache2/ssl/www_192_168_90_25_xip_io.crt”
SSLCertificateKeyFile “/private/etc/apache2/ssl/www_192_168_90_25_xip_io.key”

Getting Started with SSL – Simplified


Secure Communication is really vital for every business today and Secure Socket Layer (SSL) is one of the most used mechanisms to perform this task. In this writing I will just give a brief concept about SSL, there are different variations to this according to your usage.

Before talking about SSL, Let us introduce some people who will help us talk about cryptography and SSL/TLS.

Alice  – A normal person like us who wants to communicate with Bob.

Bob – Another normal person like us who wants to communicate with Alice.

Eve – Fascinated by Alice and Bob and she wants to eavesdrop on what they are talking about.

Mallory – A malevolent person, who not only tries to listen to what Alice and Bob are talking about but also tries to alter, delete and substitute their messages by fooling them. He is known as the man in the middle.

Long Time Ago



Back in time around 1981, Data Encryption Standard (DES) was published as a symmetric algorithm. It was used with the 56 bit key that could be shared but kept secret. Once the key was agreed on, all of their communications would be opaque to man in the middle.

There was one problem – how could they agree on a key? Alice couldn’t send a key to Bob because both Eve and Mallory would see it as she had to send it unencrypted. After that, Mallory could intercept messages from Alice to Bob, decrypting them with the real key, reading them, then encrypting them with the fake key and sending them on. The same thing would happen on the return journey. Alice and Bob’s messages would be nowhere near secure.

So the best was to share the key for them is to meet in person and decide the key and even if that key gets hacked then again meet up and decide new key. (By the way, Alice and Bob are living very far from each other).

Some Time Ago

Standard DES has been supplanted with variations (triple-DES) and new algorithms (AES) with longer keys, but for Alice and Bob, the same old problem is still present: how to agree on and exchange a key securely.

Even though they were already facing difficulty in communication and with advancements of computers the malevolent man in the middle become fast enough to brute force the decryption of DES, thus the public key cryptography was invented.With public key cryptography, things are different. Public key cryptosystems use two separate keys: a public key and a private key. The cryptosystem (the most famous one is RSA, named after its inventors Rivest, Shamir, and Adleman) uses special mathematical algorithms so that the encryption of a plain text message and the decryption of that encrypted message use different keys.

The keys are related mathematically, but knowing one doesn’t really help you discover the other, Because there are different keys for encrypting and decrypting, these cryptosystems are known as asymmetric algorithms. This is how Alice would encrypt a message to send to Bob with a public key algorithm.

Both she and Bob have private/public key pairs, properly generated according to the algorithm they’re using. Alice will encrypt the plain text message with her private key (known only to her), and then encrypt the result of that with Bob’s public key. She knows Bob’s public key because he publishes it (similarly she publishes her own public key).

She then sends this twice-encrypted message to Bob. He receives the encrypted message from Alice. He then decrypts the message with his private key (this key is a secret known only to him) and then decrypts the result of that with Alice’s public key.

If the result is legible, he knows a couple of things with certainty: only he could read it (neither Eve nor Mallory could, since only his private key could decrypt it), and Mallory couldn’t have slipped in a fake message since the original message could only have been encrypted with Alice’s private key. So everything is well, and he and Alice can communicate with abandon.


In fact, since public key crypto-systems are much slower at encrypting and decrypting than symmetric algorithms, in general only one message is sent using a public key cryptosystem: which is a randomly generated key for a symmetric algorithm and used for further communication.

All of a sudden, Alice and Bob’s original problem with a symmetric encryption algorithm is removed: Alice just sends Bob a brand new 256-bit key encrypted using RSA in the manner I just described, and then they communicate using AES with that 256-bit key. They don’t have to meet at all.

It sounds full proof but still one flaw: how do Alice and Bob exchange their public keys securely? Alice can’t send an unencrypted message to Bob containing her public key, because Mallory may intercept that message and substitute his own public key. (Ditto for Bob informing Alice of his public key.) If that did happen, Mallory would be in complete control of the message channel.

Let’s call the two key pairs that Mallory generates, fakeAlice and fakeBob; Alice thinks fakeBob is actually Bob, and Bob thinks fakeAlice is Alice. Suppose Alice sends a message to Bob. She encrypts it with her private key and then with fakeBob’s public key and then sends it.

Mallory gets it, decrypts it with the fakeBob’s private key and with Alice’s public key, and reads the message. He then encrypts a new message with fakeAlice’s private key and Bob’s public key and sends it to Bob. Bob can decrypt it with his private key and fakeAlice’s public key.

Alice and Bob still have to meet in order to exchange their public keys. We’re no better off than we were before.

Secure Sockets Layer: A Superhero!!

In practice, this problem is solved by one more level of indirection: the CA or certificate authority.

A CA issues digital certificates that identify a particular person or entity and the public key used by that person or entity. In essence, a digital certificate is a name (usually a domain name) and the associated public key encrypted by the CA’s private key. You can check the validity of a certificate by decrypting it with the CA’s public key.

But still one question comes to the mind, how do Alice and Bob know the CA’s public key? Can’t Mallory just intercept this and replace with his own public key?

Technically yes, but in practice, the CA’s public key is provided as a certificate with the browser or as part of the operating system. CA certificates are truly publicly published. You trust that these certificates are valid because they’re delivered to you with your operating system or browser.

Once Alice and Bob buy their digital certificates from a particular CA, they can send them to each other with impunity, in essence by trusting the CA. Alice can check Bob’s certificate (and discover his public key) by decrypting it with the CA’s certificate, and vice versa. Once that’s done, they can send each other secure messages.

In a crux

  • Assume Alice and Bob both have public and private keys
  • If Alice encrypts something with Bob’s public key, she ensures that only Bob can decrypt it (using his private key)
  • If Alice encrypts something with her own private key, anyone can decrypt it (using her public key), but they will know that it was encrypted by her
  • Therefore, if Alice encrypts a message first with her own private key, then with Bob’s public key, she will ensure that only Bob can decrypt it and that Bob will know the message is from her.

Regarding SSL certificates, here’s what is important to know:

  • You generate a request for a certificate. In that request, you put your own public key and a bunch of information about yourself like company name, email etc.
  • The certificate issuer (in theory) checks you out to make sure it knows who you are and are you a secure channel or not.
  • If they’re satisfied, the certificate issuer then encrypts the hash of your request with their private key. Anyone who decrypts it with their public key knows that they vouch for the information it contains: they agree that the public key is your and that the information stated is true about you. This encrypted endorsement is the certificate that they issue to you.
  • When somebody connects to your site or server, You send them the certificate.
  • Their browser/OS already knows the issuer’s public key because their browser/OS came installed with that information.
  • Their browser uses the issuer’s public key to decrypt what you sent to them. The fact that the issuer’s public key works to decrypt it proves that the issuer’s private key was used to encrypt it, and therefore, that the Issuer really did create this certificate.
  • Inside the decrypted information is your public key, which they now know has been vouched for. They use that to encrypt some data to send to you.

It should be noted that the whole system is essentially a technical implementation of the idea “you trust the certificate issuer, and they trust me, therefore you can trust me.” Unfortunately, sometimes the certificate issuer isn’t trustworthy (like the case of DigiNotar which led to almost 300,000 Gmail users hack)