# Cryptography (1–5 Levels)

Hey, I know you are probably scared of Cryptography, let’s be honest, you probably are not familiar or you think you know it but you don’t. A subject which I have learned as it only gets interesting once you get it. Let me teach you the wonders to this field and fast.

Prerequisites:

Level 1,2 (No prior knowledge)

Basic understanding of networks.(Level 3)

MATHS(upto 11th)- Later parts(Level 4,5)

Bit of programming.Level(4,5)

(LEVEL 4,5)Note: I will not cover the basics which come before cryptography. A checkpoint is made, if you are unfamiliar with any of the following, then you lack basic understanding of modern standards of security, I will try my best to make you understand this concept fast.

OID,CA, PKI,HSM,DRA,RA,Trust Model, Hierarchical Trust Model,Bridge Trust Model,Certificate Chaining, CRL, OCSP

Introduction and puzzles:(Level 1)

So what exactly is cryptography one may ask? Let’s take an example, you are sending a gift to your father, so you put it inside a box, now when you post it there is a problem. The mailman can simply open the box and steal the gift. The next idea would be to lock it and send the key separately to your father thereby preventing the mailman to open the box and steal the gift!

So you solved a problem, you prevented your gift or private information’s exposure to an unauthorized person(mailman)! Cryptography is similar but we do it in the digital world:

Mail = DATA/PAYLOAD

YOU = Sender

DAD = RECEIVER

MAILMAN = Unauthorized Person(HACKER)

Box = Protocol

LOCK = Algorithm

Key = Key

Cool! Now you know about Cryptography, script kiddies can leave now and rest keep reading because things will get interesting.

**Cryptography before Jesus Christ(LEVEL 2)**

Now let’s talk about digital cryptography, a bit of background is important. Julius Caesar used to substitute alphabets in his secret letters, for example he would substitute “D” by “T” thus DOG became TOG. Inspired by this we have ROT13 where every alphabet is moved by 13 places for example DOG is QBT, these are called substitution ciphers. There is a problem, the problem is everyone who knows the substitution can decrypt it and get the data.

**MODERN CRYPTOGRAPHY:**

So things get bit interesting here, after computers came into existence so came people to poke around, that is hackers and a problem to keep data safe was already a issue but bigger was how to send it safely.

We have variety of systems to implement to keep data secure but mostly you need to know about 2!

**ENCRYPTION**:

First, let's talk about encryption, remember the caesar's cipher? Well we took clear information and turned it into a secret that could only be read by people who knew how to solve the secret. Similarly, we have digital encryption, this is a process where we take your data and try to turn it into secret data ie(Encrypted data/Cipher Text/Message Digest) that could then be decrypted only by an authorized person to read that data.

SYMMETRIC ENCRYPTION: Remember the mailman problem?,You solved it well. Now here we apply it, send the data to your father and key separately. But now again, what if the key gets stolen by your mailman? Yup, he can open the box and steal the gift. Then one might ask that why should we use it? Pretty simple because its convenient, if you’re lazy and the data is not very confidential then you might use it, because its fast and convenient. Here the key is called a private key. So Symmetric algorithms are exactly same concept, they all have a key which has to be given in order to unlock the lock. Think of it like your Door’s lock, All your family members have access to the keys and thus it safe but one might lose the key and your entire home is compromised.

Symmetric Algorithms include DES.BLOWFISH, AES, TWOFISH, RC4, and so on.

Another thing that most people forget is the key complexity, always remember that in security, the biggest problem is convenience and that's why people have weak passwords and we still use small keys like DES 56bit. Think of it as a magic lock, the bigger the key size, the bigger the lock, and thus the more time it will take to unlock it. So you choose convenience or confidentiality:)

**Key Stretching:**

A thing to consider is that you can have multiple locks with multiple different key to make it more secure, similarly, in symmetric encryption we call it as key stretching where the data is encrypted multiple times often by multiple algorithms to make it more secure:)

We can also use Symmetric Algorithms securely but that will be later in the post;)

**Asymmetric Encryption:**

Now we had issues with symmetric encryption, the issue was there was a single key that would lock and unlock the lock thus if that key fell into wrong hands then your information is compromised. Asymmetric Encryption solves that very issue. Here instead of one key, we use two keys but its different from key stretching by that the keys are derived but not directly related to each other. Let me explain:

In Asymmetric Encryption we have 2 Keys, 1 is private and the other is public. The trick is that the public key is derived or made out of part of the private key but if you have the public key, you cannot make a private key as you don’t know the rest of the information. This is vague to keep it simple. So you want to send a mail to your father again but this time the mailman might steal the key. No worries, Asymmetric encryption is at the rescue. Both you and your father generate 2 keys, 2 for him and 2 for you 2+2=4. Now as the name suggest the public key is for the public, so you ask your father for his public key and you take the mail and use the public key of your father to lock it. The mailman also asks your father for his public key and he gets it. You might ask, will he be able to open the box? NOPE!, the beauty here is that the public key can only lock the information, so it can only lock the box but not unlock it, so who can? Remember that both keys belong to your father, since you used his public key to encrypt the information, he can use it to decrypt it or open the lock since the public key is derived from the private key. Now if your father wants to mail the gift back since he does not like it, he will use your public key to lock it(encrypt) and you can use your private key to unlock(decrypt) it. The mailman is sad since he thought he could use the public key to unlock it:(

REMEMBER THE RULE:

PUBLIC KEY = ENCRYPT

PRIVATE KEY = DECRYPT

So now that you have your concept clear, lets talk about which algorithms uses asymmetric encryption:

Rivest, Shamir, and Adelman (RSA): RSA is named after the three people who invented the algorithm. The keys were the first private and public key pairs, and they start at 1,024, 2,046, 3,072, and 4,096 bits. They are used for encryption and digital signatures.

Digital Signature Algorithm (DSA): DSA keys are used for digital signatures; they start at 512 bits, but their 1,024-bit and 2,046-bit keys are faster than RSA for digital signatures.

Elliptic Curve Cryptography (ECC): ECC is a small, fast key that is used for encryption in small mobile devices. However, AES-256 is used in military mobile cell phones. It uses less processing than other encryptions. Ephemeral Keys: Ephemeral keys are short-lived keys. They are used for a single session, and there are two of them:

a. Diffie Hellman Ephemeral (DHE)

b. Elliptic Curve Diffie Hellman Ephemeral (ECDHE)

Pretty Good Privacy (PGP): PGP is used between two users to set up an asymmetric encryption and digital signatures. For PGP to operate, you need a private and public key pair. The first stage in using PGP is to exchange the keys. It uses RSA keys.

GnuPG: GnuPG is a free version of OpenPGP; it is also known as PGP. It uses RSA keys.

**DIGITAL SIGNATURES:**

Remember the rule? Well, rules are meant to be broken, what if we use our private key to encrypt the data? Then since everyone who has our public key can decrypt the data. Then what's the purpose one may ask? Well if someone can use your public key to decrypt your data then it means the data has was never tampered with, what do I mean? since no one has access to your private keys then the data must be yours since everyone is able to decrypt it using your public key which is derived from your private keys. This is called **Nonrepudiation.**

Thus you cannot claim that the data is not yours since you signed it with your private key, what if someone steals your private key and signs the data? BAD LUCK:(

PRO TIP: Cybersecurity has two problems, confidentiality and convenience, you can choose either one but not both.

**Symmetric vs Asymmetric Encryption:**

Symmetric is fast but due to that it has less security since it only used a private key or shared key. If someone steals the key then, information is compromised. It is 100–1000x faster than Asymmetric Encryption:0

Asymmetric is slower but it has two sets of keys also called PKI thus offering more security as, if the shared key(public) is stolen, then information is still safe as an only a private key can decrypt the information:)

**Cipher Modes:(Level 3)**

There are different cipher modes; most symmetric keys use a block cipher and can encrypt a large amount of data quicker than asymmetric encryption. Let’s look at these in turn:

** Stream Cipher**: A stream cipher is a method of encrypting text (to produce ciphertext) in which a cryptographic key and algorithm are applied to each binary digit in a data stream, one bit at a time. It is normally used by asymmetric encryption. This is slow and uses XOR(Level 4,5) function to create ciphertext.

*Block Cipher**:* A block cipher is where a block of data is taken and then encrypted; for example, 128 bits of data may be encrypted at a time. This is the method used today as it is much faster than a stream cipher. It is used by symmetric encryption with the exception of RC4. Let’s say you have 1 Mb of data ie 1024 Kb thus we can break it down to 16 blocks of 64 bytes each. 16x64=1024.

**How they work:**

Modes of operation are how ciphers work to achieve encryption. Let’s look at the different modes:

Initialization Vector (IV): This is a (pseudo)random value used as a secret key for data encryption. This number, also called a nonce, is employed only one time in any session. The IV length is usually comparable to the length of the encryption key or the block of the cipher in use. Sometimes, this is also known as a starter variable.

Cipher Block Chaining (CBC): CBC adds XOR(LEVEL 4,5) to each plaintext block from the ciphertext block that was previously produced. The first plaintext block has an IV that you XOR, and you then encrypt that block of plaintext.The next block of plaintext is XOR’d against the last encrypted block before you encrypt this block. When decrypting a ciphertext block, you need the XOR from the previous ciphertext block. If you are missing any blocks, then decryption cannot be done.

Electronic Code Book (ECB): ECB replaces each block of the clear text with the block of ciphertext. The same plaintext will result in the same ciphertext. The blocks are independent from the other blocks. CBC is much more secure.

Galois/Counter Mode (GCM): This is a block cipher mode of operation that uses universal hashing over a binary Galois field to provide authenticated encryption. It can be implemented in hardware and software to achieve high speeds with low cost and low latency.

Counter Mode (CTR): CTR turns a block cipher into a stream cipher. It generates the next keystream block by encrypting successive values of a counter rather than an IV.

**XOR Encryption(Internal Working){LEVEL 4}:**

Before i start, congrats you’ve made it so far, i would like to thank Mukul Sir who around a year back, taught few of the lucky ones what XOR gates and how they work. I have since many books on XOR and took me some time to understand it.

**Introduction to classical Electronics:**

Well computer are not that smart, they can only understand 2 operations, in programming we call this boolean operator or TRUE/FALSE operators. Computers work on binary, ie 0 and 1. where 1 represents true and 0 represents false. Through total of 7 gates or operations, every single task on a computer is performed, they are **AND, OR, XOR, NOT, NAND, NOR, and XNOR **respectively.

Let’s eat only what we can swallow as discuss about XOR:

**XOR and TRUTH TABLES:**

“XOR” an abbreviation for “Exclusively-OR.” The simplest XOR gate is a two-input digital circuit that outputs a logical “1” if the two input values differ, i.e., its output is a logical “1” if either of its inputs are 1, but not at the same time (exclusively). The symbol and truth table for an XOR is shown below. The Boolean expression for a two-input XOR gate, with inputs A and B and output X:

To simplify, you pass two arguments(Plaintext in binary and key in binary) and if they both are identical then following the rules of the truth table, the output will be given. If both are the same we write “0” and if they are different we write “1”. Pretty simple? Go and Learn about the 6 remaining.

*XOR implementation in XOR encryption:*

Now that we have learnt about XOR, lets talk about encryption with it, here how we implement it. As previously discussed, XOR can only take in binary but you might not know how its done, so let me walk you through. (SKIP if you’re from ISC/ICSE)

Every key you use on your keyboard has two notation, one is the notation you use and another one is ASCII:

How does ASCII work? Pretty simple, look at the table, you know that the English alphabet has 26 letters which makes up all words you speak in English. In ASCII the representation of alphabets begins from 65, why? Because there are other stuff in your computers which i will not discuss here. To conclude, “A” = 65 in ASCII, B is “66” and Z is “90”, note the upper case.

So now that's clear but how do we get it to binary? well the logic is pretty simple, suppose you want to convert “A” to binary to perform XOR encryption, to convert, you can simply see that A = 65. We can now convert 65 into binary. If you don’t know how to do that well ill teach you:

There are two ways, one is with Maths and another one is without maths.

Lets do without maths for today:

A = 65

Now first we set up a table, the table has increasing two raise to the power. Since its binary. Now taking the character A = 65, we can put it in the following table. 65–128= would make a negative thus we reject it. We go with 65–64 = 1 since we can completely subtract, we allow write a 1 at 64 denoting true or success. Now remainder 1 cannot be subtracted by 32,16,8,4,2 since its smaller thus we write 00000 denoting false, or unsuccessful, lastly 1–1=0, since we can subtract and not get a negative result we write TRUE = 1

PROTIP: You cannot subtract and get negative. 1=true and 0 = false

Thus our chart looks like:

128 = 0

64 = 1

32=0

16=0

8=0

4=0

2=0

1=1

Thus if you write it in one line we get 1000001, note we do not write 0 at first.

Now you know the background logic, feel free to boast this. Here’s a simple program i wrote back in class 8 in java to convert characters to ascii. This logic is called explicit typecasting. Pick up a Sumita Arora and get these concepts cleared.

Now we take a random binary key and XOR it with the character “z=122”, lets try it out with z. Following the truth tables, this will be a piece of cake. Now this key we are talking about is Pseudo Randomly generated ie, unknown so XORing both will give us a binary output.

Practical: XORing z=122 = 01111010 with Key 01010101

There is a problem here, you guessed it. If the key gets leaked then one can decrypt the message and that is the essence of cryptography.

Protip: Try to reverse the XORed output by using key.

**Turning Symmetric Encryption Secure(Level 5):**

If you have come so far, congratulations. Now as you know by now that symmetric Encryption is not secure due to the risk of the key being stolen well, there exists a hybrid solution. What if we can securely send the key through asymmetric encryption and use fast symmetric encryption to send the messages?

Welcome to the world of DH or Diffie-Hellman Key Exchange. Ever wondered when you’re trying to log into ssh why does the word Diffie-Hellman is tossed around?

Why is Diffie Helman?

Diffie Hellman (DH) does not encrypt data. Its main purpose is to create a secure session so that symmetric data can travel down it. DH creates the keys used in the Internet Key Exchange (IKE); it uses UDP port 500 to set up the secure session for the L2TP/IPSec VPN. Once the secure tunnel has been created, then the symmetric encrypted data flows down the tunnel.

This is genius but wait you also need to know internal workings, welcome more maths:

**How does it work?**

For completing a secure tunnel, the algorithm assumes a prime number, for example, q and select its primitive root, so lets choose alpha as the primitive root of q. The condition being that alpha has to be less than q. What exactly is a primitive root? (denoting alpha as a)

Well alpha is a primitive root of q if:

*a mod q, a²mod q, a³ mod q , a⁴ mod q …….a^q-1 mod q = 1,2,3…q-1*

Now lets the generate the public and private key of USER A.

Now assuming X is the private key, we have to make sure that Xa<q

Now the public is denoted by Y. Thus we use the Formula to get the public key= Ya = alpha^Xa mod q.THUS {Xa,Ya}

And we have both, pretty simple if you have a good understanding of maths.

Now the same process for User B.

Now, sender, each group has 3 things Xa,Yb, and prime number q.

We simply we the formula for A k =(YB)^xA Mod q

Same for user B.

Now you know how Diffie hellman key exchange works!

Cryptography is vast and cannot be summed up into one post or even a book. I tried to explain and cover almost all aspects. Next, we can look over some cryptographic mathematical attacks and also break down some use cases. If you want go to liveoverflow and watch the google hacking cup challenge and learn about ECB block cipher attacks. Here’s a simple breakdown of coppersmith:https://acmccs.github.io/papers/p1631-nemecA.pdf

Thank you all for reading. I wrote this in one sitting to might have minor mistakes though im a perfectionist. Keep Learning:)

As Aristotle once said and i quote:

We are what we repeatedly do. Excellence, then, is not an act, but a habit