You are on page 1of 91

WEEK-1 24.01.

2023

CAESAR CIPHER TECHNIQUE

Aim: To implement the CAESAR CIPHER technique or Algorithm.

Pre-Requisite:
When you are sending a text message to a friend, you don’t want your message to be
manipulated or misused by an intruder. In order to avoid this, we need to convert the plain
text data to a ciphertext. Before getting into this conversion let us first know what a cipher
model is.
Symmetric CIPHER model:
A symmetric encryption scheme has five basic ingredients :

■ Plaintext: This is the original intelligible message or data that is fed into the algorithm as
input.

■ Encryption algorithm: The encryption algorithm performs various substitutions and


transformations on the plaintext.

■ Secret key: The secret key is also input to the encryption algorithm. The key is a value
independent of the plaintext and of the algorithm. The algorithm will produce a different
output depending on the specific key being used at the time. The exact substitutions and
transformations performed by the algorithm depend on the key.

■ Ciphertext: This is the scrambled message produced as output. It depends on the plaintext
and the secret key. For a given message, two different keys will produce two different
ciphertexts. The ciphertext is an apparently random stream of data and, as it stands, is
unintelligible.

■ Decryption algorithm: This is essentially the encryption algorithm run in reverse. It takes
the ciphertext and the secret key and produces the original plaintext.

Execution:

1. Absolute path of the folder: F:\NSC_1225


2. System: GVPCE (A)/IT/Lab1/Sys30
3. MAC ADDRESS: 94-E2-3C-39-74-F7

20131A1225 1
WEEK-1 24.01.2023

Description:
The two basic building blocks of all encryption techniques are substitution and
transposition.
Substitution Technique:
A substitution technique is one in which the letters of plaintext are replaced by other
letters or by numbers or symbols. If the plaintext is viewed as a sequence of bits, then
substitution involves replacing plaintext bit patterns with ciphertext bit patterns.
The Caesar cipher is a kind of replacement (substitution) cipher, where all letter of plain
text is replaced by another letter.
CAESAR CIPHER :
 The Caesar cipher is the simplest and oldest method of cryptography.
 The Caesar cipher method is based on a mono-alphabetic cipher and is also called a
shift cipher or additive cipher.
 Julius Caesar used the shift cipher (additive cipher) technique to communicate with
his officers.
 For this reason, the shift cipher technique is called the Caesar cipher.

Procedure:
 Each letter of a given text is replaced by a letter with a fixed number of
positions down the alphabet. For example with a shift of 1, A would be
replaced by B, B would become C, and so on.

 Thus to cipher a given text we need an integer value, known as a shift which
indicates the number of positions each letter of the text has been moved down.

20131A1225 2
WEEK-1 24.01.2023

The formula of encryption is:

En (x) = (x + n) mod 26

The formula of decryption is:

Dn (x) = (x - n) mod 26

Note: If any case (Dn) value becomes negative (-ve), in this case, we will
add 26 in the negative value.

E denotes the encryption


D denotes the decryption
X denotes the value of the letter as shown in the following figure
N denotes the key value (shift value)

Advantages of Caesar cipher:


Its benefits are as follows:
1. It is very easy to implement.
2. This method is the simplest method of cryptography.
3. Only one short key is used in its entire process.
4. If a system does not use complex coding techniques, it is the best method for it.
5. It requires only a few computing resources.

Disadvantages of Caesar cipher:


Its disadvantages are as follows:
1. It can be easily hacked. It means the message encrypted by this method can be easily
decrypted.
2. It provides very little security.
3. By looking at the pattern of letters in it, the entire message can be decrypted.

20131A1225 3
WEEK-1 24.01.2023

Execution:

The code for Caesar Cipher in python is as follows:


#ENCRYPTION
def encrypt(inp,n):
  cipher=""
  for char in inp:
    if(char.islower()):
      cipher+=chr((ord(char)-97+n)%26+97)
    else:
      cipher+=chr((ord(char)-65+n)%26+65)
  return cipher
 
#DECRYPTION
def decrypt(out,n):
  return encrypt(out,-n)

#DRIVER CODE
plain_text=input("Enter the plain text: ")
n=int(input("Enter the no of shifts to be done:"))
result=encrypt(plain_text,n)
print("The encrypted text is: " +result)
cipher_text=input("Enter the encrypted text: ")
print("The text after decryption is :"+ decrypt(cipher_text,n))

Output:

HACKING THE CAESAR CIPHER WITH BRUTE-FORCE:


We can hack the Caesar Cipher by using a cryptanalytic technique called brute force.
 A brute force attack tries every possible decryption key for a cipher.
 Nothing stops a cryptanalytic from guessing one key, decrypting the cipher text with
that key looking at the output, and then moving on to the next key if they did not find
the secret message.
 Because the brute force technique is so effective against the Caesar Cipher, you
should not actually use the Caesar Cipher to encrypt the secret information.

20131A1225 4
WEEK-1 24.01.2023

Program:
txt=input("Enter the data to be hacked:")

def hack(txt):

  txt=txt.upper()
  letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  for i in range(0,26):
    msg=""
    for j in txt:
      if j in txt:
        msg+=chr((ord(j)-65-i)%26+65)
      else:
        msg+=j
    print(msg)
hack(txt)

OUTPUT:

Signature

20131A1225 5
WEEK-1 7.02.2023

HILL CIPHER TECHNIQUE


Aim: To implement the HILL CIPHER technique or Algorithm.

Pre-Requisites:
Hill cipher uses matrix multiplication in order to encrypt the given plain text.

So it requires prerequisite knowledge of matrix algebra besides linear algebra.

Description:
 The Hill Cipher method was invented and developed in 1929 by Lester S. Hill, a
renowned American mathematician.
 Hill Cipher, in the pretext of classical cryptography, follows a polygraphic
substitution cipher, which means there is uniform substitution across multiple levels
of blocks. 
 The Hill Cipher is also a block cipher. A block cipher is an encryption method that
implements a deterministic algorithm with a symmetric key to encrypt a block of text.
It doesn’t need to encrypt one bit at a time like in stream ciphers.

Procedure:
 Each letter is represented by a number modulo 26.
 Often the simple scheme A = 0, B = 1, …, Z = 25 is used, but this is not an essential
feature of the cipher.

 To encrypt a message, each block of n letters (considered as an n-component vector)


is multiplied by an invertible n × n matrix, against modulus 26.
 To decrypt the message, each block is multiplied by the inverse of the matrix used
for encryption.
 The matrix used for encryption is the cipher key, and it should be chosen randomly
from the set of invertible n × n matrices (modulo 26).

20131A1225 6
WEEK-1 7.02.2023

To encrypt the text using hill cipher, we need to perform the following operation.

E(K, P) = (K * P) mod 26  

Where K is the key matrix and P is plain text in vector form. Matrix multiplication of K and
P generates the encrypted ciphertext.

Steps For Encryption

Step 1: Let's say our key text (2x2) is DCDF. Convert this key using a substitution scheme
into a 2x2 key matrix as shown below:

Step 2: Now, we will convert our plain text into vector form. Since the key matrix is 2x2, the
vector must be 2x1 for matrix multiplication. (Suppose the key matrix is 3x3, a vector will be
a 3x1 matrix.)

In our case, plain text is TEXT that is four letters long word; thus we can put in a 2x1 vector
and then substitute as:

Step 3: Multiply the key matrix with each 2x1 plain text vector, and take the modulo of result
(2x1 vectors) by 26. Then concatenate the results, and we get the encrypted or ciphertext
as RGWL.

20131A1225 7
WEEK-1 7.02.2023

Decryption

To encrypt the text using hill cipher, we need to perform the following operation.

1. D(K, C) = (K-1  * C) mod 26  

Where K is the key matrix and C is the ciphertext in vector form. Matrix multiplication of
inverse of key matrix K and ciphertext C generates the decrypted plain text.

Steps For Decryption

Step 1: Calculate the inverse of the key matrix.

First, we need to find the determinant of the key matrix (must be between 0-25). Here the
Extended Euclidean algorithm is used to get modulo multiplicative inverse of key matrix
determinant.

Step 2: Now, we multiply the 2x1 blocks of ciphertext and the inverse of the key matrix. The
resultant block after concatenation is the plain text that we have encrypted i.e., TEXT.

20131A1225 8
WEEK-1 7.02.2023

Execution:
import numpy as np
def encryption(m):
    # Replace spaces with nothing
    m = m.replace(" ", "") 
    # Ask for keyword and get encryption matrix
    C = make_key()
    # Append zero if the messsage isn't divisble by 2 
    if(len(m)%2!=0):
        m +="0"
    # Populate message matrix
    P = create_matrix_of_integers_from_string(m)
    # Calculate length of the message
    m_len = int(len(m) / 2)
    # Calculate P * C
    en_m = ""
    for i in range(m_len):
        # Dot product
        row_0 = P[0][i] * C[0][0] + P[1][i] * C[0][1]
        # Modulate and add 65 to get back to the A-Z range in ascii
        integer = int(row_0 % 26 + 65)
        # Change back to chr type and add to text
        en_m += chr(integer)
        # Repeat for the second column
        row_1 = P[0][i] * C[1][0] + P[1][i] * C[1][1]
        integer = int(row_1 % 26 + 65)
        en_m += chr(integer)
    return en_m
    
def decryption(en_m):
    # Ask for keyword and get encryption matrix
    C = make_key()
    # Inverse matrix
    determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0]
    determinant = determinant % 26
    multiplicative_inverse = find_multiplicative_inverse(determinant)
    C_inverse = C
    # Swap a <-> d
    C_inverse[0][0], C_inverse[1][1] = C_inverse[1, 1], C_inverse[0, 0]
    # Replace
    C[0][1] *= -1
    C[1][0] *= -1
    for row in range(2):

20131A1225 9
WEEK-1 7.02.2023
        for column in range(2):
            C_inverse[row][column] *= multiplicative_inverse
            C_inverse[row][column] = C_inverse[row][column] % 26
    P = create_matrix_of_integers_from_string(en_m)
    m_len = int(len(en_m) / 2)
    de_m = ""
    for i in range(m_len):
        # Dot product
        column_0 = P[0][i] * C_inverse[0][0] + P[1][i] * C_inverse[0][1]
        # Modulate and add 65 to get back to the A-Z range in ascii
        integer = int(column_0 % 26 + 65)
        # Change back to chr type and add to text
        de_m += chr(integer)
        # Repeat for the second column
        column_1 = P[0][i] * C_inverse[1][0] + P[1][i] * C_inverse[1][1]
        integer = int(column_1 % 26 + 65)
        de_m += chr(integer)
    if de_m[-1] == "0":
        de_m = de_m[:-1]
    return de_m

def find_multiplicative_inverse(determinant):
    multiplicative_inverse = -1
    for i in range(26):
        inverse = determinant * i
        if inverse % 26 == 1:
            multiplicative_inverse = i
            break
    return multiplicative_inverse

def make_key():
     # Make sure cipher determinant is relatively prime to 26 and only a/A - z/Z are given
    determinant = 0
    C = None
    while True:
        cipher = input("Input 4 letter cipher: ")
        C = create_matrix_of_integers_from_string(cipher) # key matrix made here  
        determinant = C[0][0] * C[1][1] - C[0][1] * C[1][0]
        determinant = determinant % 26
        inverse_element = find_multiplicative_inverse(determinant)
        if inverse_element == -1:
            print("Determinant is not relatively prime to 26, uninvertible key")
        elif np.amax(C) > 26 and np.amin(C) < 0:
            print("Only a-z characters are accepted")
            print(np.amax(C), np.amin(C))
        else:
            break
    return C

20131A1225 10
WEEK-1 7.02.2023

def create_matrix_of_integers_from_string(string):
    # Map string to a list of integers a/A <-> 0, b/B <-> 1 ... z/Z <-> 25
    integers = [chr_to_int(c) for c in string]
    length = len(integers)
    M = np.zeros((2, int(length / 2)), dtype=np.int32)
    iterator = 0
    for column in range(int(length / 2)):
        for row in range(2):
            M[row][column] = integers[iterator]
            iterator += 1
    return M

def chr_to_int(char):
    # Uppercase the char to get into range 65-90 in ascii table
    char = char.upper()
    # Cast chr to int and subtract 65 to get 0-25
    integer = ord(char) - 65
    return integer
m = input("Message: ")
en_m = encryption(m)
print(en_m)
de_m = decryption(en_m)
print(de_m)

OUTPUT:

20131A1225 11
WEEK-1 7.02.2023

Signature

20131A1225 12
WEEK-1 14.02.2023

SIMPLE D.E.S TECHNIQUE


Aim: To implement the simple DATA ENCRYPTION STANDARD (DES) technique
or Algorithm.

Pre-Requisite:
Simplified Data Encryption Standard is a simple version of Data Encryption
Standard having a 10-bit key and 8-bit plain text.
It is much smaller than the DES algorithm as it takes only 8-bit plain text whereas
DES takes 64-bit plain text.

Description:
Simplified Data Encryption Standard (S-DES) is a simple version of the  DES Algorithm. It
is similar to the DES algorithm but is a smaller algorithm and has fewer parameters than
DES. It was made for educational purposes so that understanding DES would become
simpler.  It is a block cipher that takes a block of plain text and converts it into ciphertext.
It takes a block of 8 bit.
It is a symmetric key cipher i.e. they use the same key for both encryption and decryption.
In this article, we are going to demonstrate key generation for s-des encryption and
decryption algorithm. We take a random 10-bit key and produce two 8-bit keys which will
be used for encryption and decryption.
Key Generation Concept : 
In the key generation algorithm, we accept the 10-bit key and convert it into two 8-
bit keys. This key is shared between both sender and receiver. 
In the key generation, we use three functions:

1.Permutation P10

2.Permutation P8

20131A1225 13
WEEK-1 14.02.2023

3.Left Shift

S-Box:
The principle of S-boxes is as follows Each S-box must have six bits of input and four bits of
output. There is no output bit of an S-box should be too near to a linear function of the input
bits. (The S-boxes are the only non-linear element of DES and their nonlinearity is the
algorithm's strength.)
Step 1: We accepted a 10-bit key and permuted the bits by putting them in the P10 table.

Step 2: We divide the key into 2 halves of 5-bit each.

Step 3: Now we apply one bit left-shift on each key

Step 4: Combine both keys after step 3 and permute the bits by putting them in the P8 table.
The output of the given table is the first key K1.

Step 5: The output obtained from step 3 i.e. 2 halves after one bit left shift should again
undergo the process of two-bit left shift.

Step 6: Combine the 2 halves obtained from step 5 and permute them by putting them in
the P8 table. The output of the given table is the second key K2.

Encryption:
Step-1:We perform initial permutation on our 8-bit plain text using the IP table. The
initial permutation is defined as

IP(k1, k2, k3, k4, k5, k6, k7, k8) = (k2, k6, k3, k1, k4, k8, k5, k7)

20131A1225 14
WEEK-1 14.02.2023
Step-2:

 After the initial permutation, we get an 8-bit block of text which we divide into
2 halves of 4 bit each.
 On the right half, we perform expanded permutation using EP table which
converts 4 bits into 8 bits.

Expand permutation is defined as

EP(k1, k2, k3, k4) = (k4, k1, k2, k3, k2, k3, k4, k1)
 We perform XOR operation using the first key K1 with the output of expanded
permutation. Again we divide the output of XOR into 2 halves of 4 bit each.
 We take the first and fourth bit as row and the second and third bit as a column for
our S boxes.
 S boxes gives a 2-bit output which we combine to get 4 bits and then perform
permutation using the P4 table. P4 is defined as

P4(k1, k2, k3, k4) = (k2, k4, k3, k1)


 We XOR the output of the P4 table with the left half of the initial permutation table
i.e. IP table. We combine both halves i.e. right half of initial permutation and output
of ip.

Step-3:

 Now, divide the output into two halves of 4 bit each.


 Combine them again, but now the left part should become right and the right part
should become left.
 Step-4:
Again perform step 2, but this time while doing XOR operation after expanded
permutation use key 2 instead of key 1.
 On the right half, we perform expanded permutation using EP table which converts
4 bits into 8 bits. Expand permutation is defined as

EP(k1, k2, k3, k4) = (k4, k1, k2, k3, k2, k3, k4, k1)
 We perform XOR operation using second key K2 with the output of expanded
permutation. Again we divide the output of XOR into 2 halves of 4 bit each.
 We take the first and fourth bit as row and the second and third bit as a column for
our S boxes.
 S boxes gives a 2-bit output which we combine to get 4 bits and then perform
permutation using the P4 table. P4 is defined as 

P4(k1, k2, k3, k4) = (k2, k4, k3, k1)

20131A1225 15
WEEK-1 14.02.2023
 We XOR the output of the P4 table with the left half of the initial permutation table
i.e. IP table. We combine both halves i.e., right half of initial permutation and output
of ip.

Step-5:
Perform inverse initial permutation. The output of this table is the cipher text of 8 bit.
Inverse Initial permutation is defined as 

IP-1(k1, k2, k3, k4, k5, k6, k7, k8) = (k4, k1, k3, k5, k7, k2, k8, k6)
Program:
class SimplifiedDES(object):
    """Simplified DES is a simplified version of DES algorithm"""

    # Key size in bits
    key_size = 10

    """ Tables for initial and final permutations (b1, b2, b3, ... b8) """
    # Initial permutation
    IP_table = (2, 6, 3, 1, 4, 8, 5, 7)

    # Final permutation (Inverse of intial)
    FP_table = (4, 1, 3, 5, 7, 2, 8, 6)

    """ Tables for subkey generation (k1, k2, k3, ... k10) """
    P10_table = (3, 5, 2, 7, 4, 10, 1, 9, 8, 6)

    P8_table = (6, 3, 7, 4, 8, 5, 10, 9)

    """ Tables for the fk function """
    # Expansion permutation
    EP_table = (4, 1, 2, 3, 2, 3, 4, 1)

    # Substitution Box 0
    S0_table = (1, 0, 3, 2, 3, 2, 1, 0, 0, 2, 1, 3, 3, 1, 3, 2)

    # Substitution Box 1
    S1_table = (0, 1, 2, 3, 2, 0, 1, 3, 3, 0, 1, 0, 2, 1, 0, 3)

    # Permutation Table
    P4_table = (2, 4, 3, 1)

    def __init__(self, key):
        self.key = key
        self.subKey1, self.subKey2 = self.generate_key(self.key)

    def _perm(self, inputByte, permTable):
        """Permute input byte according to permutation table

20131A1225 16
WEEK-1 14.02.2023
        :param inputByte: byte to permute
        :param permTable: table to use for permutation
        :returns: permuted byte
        """
        outputByte = 0
        for index, elem in enumerate(permTable):
            if index >= elem:
                outputByte |= (inputByte & (128 >> (elem - 1))) >> (index - (elem - 1))
            else:
                outputByte |= (inputByte & (128 >> (elem - 1))) << ((elem - 1) - index)
        return outputByte

    def ip(self, inputByte):
        """Perform the initial permutation on data"""
        return self._perm(inputByte, self.IP_table)

    def fp(self, inputByte):
        """Perform the final permutation on data """
        return self._perm(inputByte, self.FP_table)

    def swap_nibbles(self, inputByte):
        """Swap the two nibbles of the byte """
        return (inputByte << 4 | inputByte >> 4) & 0xFF

    def left_shift(self, keyBitList):
        """Perform a circular left shift on the first and second set of five bits
        before = | 1| 2| 3| 4| 5| 6| 7| 8| 9|10|
        after  = | 2| 3| 4| 5| 1| 7| 8| 9|10| 6|
        :param keyBitList: list of bits
        :returns: circularly left shifted list of bits
        """
        shiftedKey = [None] * self.key_size
        shiftedKey[0:9] = keyBitList[1:10]
        shiftedKey[4] = keyBitList[0]
        shiftedKey[9] = keyBitList[5]

        return shiftedKey

    def generate_key(self, key):
        """Generate the two required subkeys
        K1 = P8(LS1(P10(key)))
        K2 = P8(LS2(LS1(P10(key))))
        :param key: key to be used for encryption and/or decryption
        :returns: tuple containing first subkey and second subkey
        """
        # Convert input key (integer) into a list of binary digits
        keyList = [(key & 1 << i) >> i for i in reversed(range(self.key_size))]

20131A1225 17
WEEK-1 14.02.2023
        # Initialise permuted key list to None
        permKeyList = [None] * self.key_size

        # To fill output of P10 permutation table and input
        for index, elem in enumerate(self.P10_table):

            # P10(key)
            permKeyList[index] = keyList[elem - 1]

        # LS1(P10(key))
        shiftedOnceKey = self.left_shift(permKeyList)

        # LS2(LS1(P10(key)))
        shiftedTwiceKey = self.left_shift(self.left_shift(shiftedOnceKey))

        subKey1 = subKey2 = 0
        for index, elem in enumerate(self.P8_table):

            # Apply P8() on first subkey
            subKey1 += (128 >> index) * shiftedOnceKey[elem - 1]

            # Apply P8() on second subkey
            subKey2 += (128 >> index) * shiftedTwiceKey[elem - 1]

        return (subKey1, subKey2)

    def F(self, sKey, rightNibble):
        """Round function
        1. Expansion Permutation Box
        2. XOR
        3. Substitution Boxes
        4. Permutation
        :param sKey: subkey to be used to for this round
        :param rightNibble: right nibble of the 8 bit input to this round
        :returns: 4 bit output
        """
        # Right nibble is permuted using EP and XOR'd with first key
        aux = sKey ^ self._perm(self.swap_nibbles(rightNibble), self.EP_table)

        # Find indices into the S-box S0
        index0 = (
            ((aux & 0x80) >> 4)
            + ((aux & 0x40) >> 5)
            + ((aux & 0x20) >> 5)
            + ((aux & 0x10) >> 2)
        )

        # Find indices into the S-box S1

20131A1225 18
WEEK-1 14.02.2023
        index1 = (
            ((aux & 0x08) >> 0)
            + ((aux & 0x04) >> 1)
            + ((aux & 0x02) >> 1)
            + ((aux & 0x01) << 2)
        )

        # S0(b1b2b3b4) = the [ b1b4 , b2b3 ] cell from the "S-box" S0
        # and similarly for S1
        sboxOutputs = self.swap_nibbles(
            (self.S0_table[index0] << 2) + self.S1_table[index1]
        )

        # Apply permutation
        return self._perm(sboxOutputs, self.P4_table)

    def fk(self, subKey, inputData):
        """Apply Feistel function on data with given subkey
        :param subKey: subkey to be used to for this round
        :param inputData: 8 bit input for this round
        :returns: 8 bit output
        """
        # Divide the permuted bits into 2 halves
        leftNibble = inputData & 0xF0
        rightNibble = inputData & 0x0F

        # Apply F
        FOutput = self.F(subKey, rightNibble)

        # Return left nibble and right nibble
        return (leftNibble ^ FOutput) | rightNibble

    def encrypt(self, plaintext):
        """Encrypt plaintext with given key
        ciphertext = IP^-1( fK2( SW( fK1( IP( plaintext ) ) ) ) )
        Example::
            ciphertext = SimplifiedDES(3).encrypt(0b10101111)
        :param plaintext: 8 bit plaintext
        :returns: 8 bit ciphertext
        """
        permuted_text = self.ip(plaintext)

        first_round_output = self.fk(self.subKey1, permuted_text)

        second_round_output = self.fk(
            self.subKey2, self.swap_nibbles(first_round_output)
        )

20131A1225 19
WEEK-1 14.02.2023
        return self.fp(second_round_output)

    def decrypt(self, ciphertext):
        """Decrypt ciphertext with given key
        plaintext = IP^-1( fK1( SW( fK2( IP( ciphertext ) ) ) ) )
        Example::
            plaintext = SimplifiedDES(3).decrypt(0b10101111)
        :param ciphertext: 8 bit ciphertext
        :returns: 8 bit plaintext
        """
        permuted_text = self.ip(ciphertext)

        first_round_output = self.fk(self.subKey2, permuted_text)

        second_round_output = self.fk(
            self.subKey1, self.swap_nibbles(first_round_output)
        )

        return self.fp(second_round_output)
def decimalToBinary(n):
  return bin(n).replace("0b", "")
plaintext = 0b10010111
key = 0b1010000010
ciphertext = SimplifiedDES(key).encrypt(plaintext)
print(ciphertext)
print(decimalToBinary(ciphertext))

Output For ENCRYPTION :

ciphertext = 0b00111000
key = 0b1010000010
plaintext = SimplifiedDES(key).decrypt(ciphertext)
print(plaintext)
print(decimalToBinary(plaintext))

Output For DECRYPTION :

20131A1225 20
WEEK-1 14.02.2023

Signature
SQL INJECTIONS

Aim: To Exploit SQL injection flaws on a sample website.

Pre-Requisites:

Kali- Linux:
Kali Linux is a popular Linux-based operating system that is primarily used for
penetration testing, digital forensics, and network security assessments. It is a powerful tool
for cybersecurity professionals and ethical hackers as it comes preloaded with a variety of
powerful tools and utilities for identifying and exploiting vulnerabilities in computer systems
and networks.
Who uses Kali Linux and Why?
Kali Linux is truly a unique operating system, as its one of the few platforms openly
used by both good guys and bad guys. Security Administrators, and Black Hat Hackers both
use this operating system extensively. One to detect and prevent security breaches, and the
other to identify and possibly exploit security breaches. The number of tools configured and
preinstalled on the operating system, make Kali Linux the Swiss Army knife in any security
professionals toolbox.

Description:

Introduction:

Penetration testing:

 Kali Linux is widely used for penetration testing, which involves testing the security
of a computer system or network by simulating attacks that a malicious hacker might
use.
 Penetration testing, also known as pen testing, is a method of evaluating the security
of a computer system, network, or web application by simulating a malicious attack.
The goal of a penetration test is to identify security vulnerabilities that could be
exploited by an attacker to gain unauthorized access to system or steal sensitive data.
 Penetration testing typically involves a series of steps, which may include:

20131A1225 21
WEEK-1 14.02.2023
 Planning and reconnaissance
 Scanning
 Exploitation
 Post-exploitation
 Reporting

SQL INJECTION:
 SQL injection is a type of security vulnerability that occurs when an attacker uses
malicious SQL code to manipulate a database.
 This can allow the attacker to access or modify sensitive data, bypass
authentication or authorization checks, or even take control of the server.
Here's an example of SQL injection:
Suppose we have a website that allows users to search for products in a database
using a search form. The search form takes a user's input and uses it to construct a SQL query
that searches for products based on the input.
The SQL query might look something like this:
SELECT * FROM products WHERE name LIKE '% search_term %';
In this query, the search_term variable is used to construct the SQL query. The % characters
are used as wildcards to match any characters before or after the search term.
Now suppose an attacker wants to exploit this vulnerability by submitting a malicious
input that modifies the SQL query. The attacker could submit a search term like this:
' OR 1=1; --
This input would modify the SQL query to look like this:
SELECT * FROM products WHERE name LIKE '' OR 1=1; --%';

 SQL Injection (SQLi) is a type of an injection attack that makes it possible to execute
malicious SQL statements. These statements control a database server behind a web
application. Attackers can use SQL Injection vulnerabilities to bypass application
security measures.

20131A1225 22
WEEK-1 14.02.2023
 They can go around authentication and authorization of a web page or web
application and retrieve the content of the entire SQL database. They can also use
SQL Injection to add, modify, and delete records in the database.
 An SQL Injection vulnerability may affect any website or web application that uses
an SQL database such as MySQL, Oracle, SQL Server, or others. Criminals may use
it to gain unauthorized access to your sensitive data: customer information, personal
data, trade secrets, intellectual property, and more. SQL Injection attacks are one of
the oldest, most prevalent, and most dangerous web application vulnerabilities.

The following things might result from SQL Injection


 Hacking other person’s account.
 Stealing and copying website’s or system’s sensitive data.
 Changing the system’s sensitive data.
 Deleting system’s sensitive data.
 The user can log in to the application as another user, even as an administrator.
 Users can view private information belonging to other users e.g., details of the other
users’ profiles, transaction details, etc.
 The user could change application configuration information and the data of the other
users.
 The user could modify the structure of the database; even delete tables in the
application database.
 The user can take control of the database server and execute commands on it at will.

SQL MAP:
 SQLmap is an open-source penetration testing tool that automates the process of
detecting and exploiting SQL injection flaws in web applications.
 SQL injection is a type of vulnerability that occurs when an attacker is able to inject
malicious SQL code into a web application that interacts with a database, allowing the
attacker to manipulate the database or access sensitive data.

20131A1225 23
WEEK-1 14.02.2023

Key features of SQL map:

To use SQLmap, you first need to identify a web application that might be vulnerable
to SQL injection.

Once you have identified a potential target, you can use SQLmap to scan the
application for vulnerabilities and attempt to exploit any that are found. SQLmap has a
command-line interface and can be run on Windows, Linux, and other operating systems.

20131A1225 24
WEEK-1 14.02.2023

20131A1225 25
WEEK-1 14.02.2023

Execution:
1. Using proxy: Proxy tool is required to test SQL injection in hidden form variables.

Command: sqlmap --proxy http://172.19.10.3:80 -u


http://testphp.vulnweb.com/artists.php?artists=1 –batch

2. To retrieve database details we use the command sqlmap -u <target URL > --dbs.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 –dbs

20131A1225 26
WEEK-1 14.02.2023

3. To retrieve the list of tables from specified database. We use the command
sqlmap -u <target URL> -D <database name> --tables

Command: sqlmap --proxy http://172.19.10.3:80 -u


http://testphp.vulnweb.com/artists.php?artists=1 -D
information_schema –tables

20131A1225 27
WEEK-1 14.02.2023

4. The command sqlmap -u <target URL> -D <database name> -T<table name> --


columns will retrieve the list of columns from the specified table.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 -D acuart -T categ –
columns

5. The command sqlmap -u <target URL> -D <database name> -T<table name> -C


<column name> --dump --predict-ouput will retrieve all the data from the users
table, first the columns will be enumerated and then the data will be dumped from the
selected columns.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 -D acuart -T
pictures -C cname --dump --predict-output

6. The command sqlmap -u <target URL>--current-db will give the name of the
database that is being used.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 --current-db

20131A1225 28
WEEK-1 14.02.2023

7. The command sqlmap -u <target URL>--current-user retrieve the information about


session User.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 --current-user

8. The command sqlmap -u <target URL> -b retrieve information about database


banner.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 -b

9. The command sqlmap -u <target URL> --hostname will retrieve information about
DBMS host name.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 –hostname

20131A1225 29
WEEK-1 14.02.2023

10. The command sqlmap -u <target URL> -f will give information about DBMS exact
version, OS information, Architecture and path level.
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 –f

11. The following command gives the information about if the user is a
DATABASE ADMINISTRATOR
Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 –is-dba

12. To enumerate DBMS SCHEMA


Command: sqlmap --proxy http://172.19.10.3:80 -u
http://testphp.vulnweb.com/artists.php?artists=1 –schema

20131A1225 30
WEEK-1 14.02.2023

Signature

20131A1225 31
WEEK-1 21.02.2023

BURP SUITE

Aim: To perform Web Security Analysis on a sample website.

Pre-Requisites:

Kali- Linux:

 Kali Linux is a popular Linux-based operating system that is primarily used for
penetration testing, digital forensics, and network security assessments.
 It is a powerful tool for cybersecurity professionals and ethical hackers as it comes
preloaded with a variety of powerful tools and utilities for identifying and exploiting
vulnerabilities in computer systems and networks.

We use the BURP SUITE tool to perform various security analysis checks on a
sample website.
The website being used here is usually “TEST.PHP”

Description:

Introduction:
 Burp Suite is a popular web application security testing tool developed by
PortSwigger.
 It is widely used by security professionals to identify and exploit vulnerabilities in
web applications.
 It is used to intercept the HTTP requests that are going out throughout web
browser.

Components of BURP SUITE:


It has several components.
Few important components are listed below as shown:
 Proxy server
 Target
 Scanner
 Intruder
 Repeater
 Sequencer
 Encoder/Decoder
 Comparer
 Extender

20131A1225 32
WEEK-1 21.02.2023

Proxy Server:
 The proxy server acts as a man-in-the-middle, allowing the user to intercept and
modify HTTP requests and responses between the client and server.
 It allows the user to intercept and modify HTTP traffic between the client and server.
 This can help in identifying vulnerabilities such as cross-site scripting (XSS), SQL
injection, and other types of injection attacks.

Target:
 The Target module in Burp Suite is where you can define the scope of your web
application security testing.
 This module allows you to specify the target website or web application that you want
to test and set up the necessary configuration for your testing.

Scanner:
 The Burp Suite scanner is a powerful feature that can automatically scan web
applications for vulnerabilities. It is designed to identify security flaws such as SQL
injection, cross-site scripting, and other types of web application vulnerabilities.
 This can save time and effort by automating the vulnerability identification process.

Intruder:
 The Intruder tool in Burp Suite is designed to automate and customize attacks against
web applications.
 It can be used to test the security of an application by performing a variety of attacks
against a target, such as brute-forcing passwords, enumerating directories, and fuzzing
parameters.

Repeater:
 The Repeater tool in Burp Suite is a powerful feature that allows you to manually
repeat requests to a web application and modify them in real-time.
 It is designed to help security professionals test the security of web applications by
providing a flexible and customizable way to interact with the application.

Sequencer:
 The Sequencer tool in Burp Suite is a feature that is used to test the randomness of
tokens or session IDs used by web applications.
 It is designed to analyze the quality of randomness of such tokens by testing their
entropy, or the amount of unpredictability or randomness present in the token.

Encoder / Decoder:
 The Decoder tool in Burp Suite is a feature that is used to encode or decode data in
various formats, such as base64, URL encoding, or HTML encoding.

20131A1225 33
WEEK-1 21.02.2023
 It is designed to help security professionals and developers manipulate and analyze
data in a web application.

Comparer:
 The Comparer tool in Burp Suite is a feature that allows you to compare two pieces of
data, such as two HTTP requests or responses.
 It is designed to help security professionals and developers identify differences
between two pieces of data and understand the impact of those differences on the
behavior of the application.

Extender:
 The Extender tool in Burp Suite is a powerful feature that allows you to extend the
functionality of Burp Suite by creating your own plugins or scripts.
 It is designed to help security professionals and developers customize and automate
their testing workflows by providing a flexible and customizable way to interact with
Burp Suite.

Execution:

 Initially, the burp suit , on opening, would show the DASHBOARD as follows:

20131A1225 34
WEEK-1 21.02.2023

 We, initially set up PROXY in the USER OPTIONS for letting the BURP SUITE
get internet services as our systems are under proxy based internet.

 Under the PROXY component, turn on the intercept and open the browser. Try
opening any website in the browser. You will be asked to forward the requests in
Proxy. Keep on forwading req until the connections gets closed and the website gets
opened.
 The website on opening will get its HTTPS layer removed so that it becomes
vulnerable.

20131A1225 35
WEEK-1 21.02.2023

Now , we proceed to analyse the security of the sample website TEST.PHP


 We first try to LOGIN to the website using USERNAME and PASSWORD as
mentioned earlier

 We shall pass the username and password to the INTRUDER and try to login by
using various ATTACKS.
 The possible attacks are:

20131A1225 36
WEEK-1 21.02.2023
Sniper:

Battering Ram:

Pitch Fork:

20131A1225 37
WEEK-1 21.02.2023
Cluster Bomb:

 Next, we pass on the uname and password to the REPEATER. It sends a series of
HTTP requests in a specific sequence to test for vulnerabilities in multi-step
processes, or vulnerabilities that rely on manipulating the connection state.

 Now ,what the SEQUENCER component does is nothing but analyzing the quality of
randomness in a sample of data items. You can use it to test an application's session
tokens or other important data items that are intended to be unpredictable, such as
anti-CSRF tokens, password reset tokens, etc.

20131A1225 38
WEEK-1 21.02.2023

 Now, we move on to the component DECODER/ENCODER. It encodes or decodes


the given text to req formats for instance HTML, HEX, URL, SHA256 etc.

 Now, we go for the component COMPARER where two items are compared on the
basis of words and bytes as well.
 It indicates what is to be done so as to make both the items similar.

20131A1225 39
WEEK-1 21.02.2023

 Next comes the LOGGER. Burp Logger records all the HTTP traffic that Burp Suite
generates in real-time.
  You can use Logger to: Study the requests sent by any of Burp's tools or extensions. 

Signature

20131A1225 40
WEEK-1 28.02.2023

R.S.A ALGORITHM

Aim: To implement the RSA technique or Algorithm.

Pre-Requisite:
In order to implement the RSA technique or Algorithm, you must have a prior
knowledge of numerical algebra and modular algebra as well.
You must know the Euclidean Algorithm to calculate GCD’s and Extended Euclidean
Algorithm to calculate Modular Inverses.

Introduction:
 The RSA algorithm is the most common public-key algorithm developed by three
people namely
a. Ron Rivest
b. Adi Shamir and
c. Leonard Adleman.
 RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually
means that it works on two different keys i.e. Public Key and Private Key.
 As the name describes that the Public Key is given to everyone and the Private key is
kept private.
 The Public key is used for encryption, and the Private Key is used for decryption.
Decryption cannot be done using a public key.
 The two keys are linked, but the private key cannot be derived from the public key.
The public key is well known, but the private key is secret and it is known only to the
user who owns the key.
 It means that everybody can send a message to the user using user's public key. But
only the user can decrypt the message using his private key.

Description:

20131A1225 41
WEEK-1 28.02.2023

RSA algorithm uses the following procedure to generate public and private keys:

 Select two large prime numbers, p and q.


 Multiply these numbers to find n = p x q, where n is called the modulus for
encryption and decryption.
 Choose a number e less than n, such that n is relatively prime to (p - 1) x (q -1). It
implies that choose e so that gcd (e, φ (n)) =1 .
 The public key is <e, n>.
 A plaintext message m is encrypted using public key <e, n>. To find ciphertext, use
c=me mod n
 Here, m must be less than n. A larger message (>n) is treated as a concatenation of
messages, each of which is encrypted separately.
 To determine the private key, we use the following formula to calculate the d such
that:
De mod φ (n) = 1
 The private key is <d, n>. A ciphertext message c is decrypted using private key <d,
n>. To calculate plain text m from the ciphertext c following formula is used
m = cd mod n

The Strength of RSA:

 The idea of RSA is based on the fact that it is difficult to factorize a large integer.
 The public key consists of two numbers where one number is a multiplication of two
large prime numbers.
 And private key is also derived from the same two prime numbers.
 So if somebody can factorize the large number, the private key is compromised.
 Therefore encryption strength totally lies on the key size .
 If we double or triple the key size, the strength of encryption increases exponentially.
 RSA keys can be typically 1024 or 2048 bits long
 But experts believe that 1024-bit keys could be broken in the near future.
 Till now it seems to be an infeasible task.

20131A1225 42
WEEK-1 28.02.2023

Program:
def gcd(a,b):
  if a<b:
    a,b=b,a
  while(True):
    rem=a%b
    if(rem==0):
      return b
    else:
      a=b
      b=rem

p=int(input("Enter a Prime Number:"))
q=int(input("Enter another Prime Number:"))
n=p*q 
print("The value of n is:",n)  

phi=(p-1)*(q-1)      #Calculate Totient Function 
print("The totient function value is:",phi)

#Choose e such that GCD(e,phi)=1 which will be the PUBLIC KEY (1<e<phi) 
e=2
while(e<phi):
  if gcd(e,phi)==1:
    break
  else:
    e+=1
print("The value of e is:",e)

#Choose d which serves as the PRIVATE KEY


d=1
for i in range(phi):
  if (i*e)%phi==1:
    d=i
    break
print("The value of d is:",d)
print("The Public key is",(e,n))
print("The Private Key is",(d,n))

#Encryption Function
def encrypt(m):
  return pow(m,e)%n
 
#Decrption Function
def decrypt(c):
  return pow(c,d)%n

20131A1225 43
WEEK-1 28.02.2023
msg=int(input("Enter the message to be encrypted(message should be <n):"))
cipher=encrypt(msg)
original_msg=decrypt(cipher)
print("The cipher text generated is:",cipher)
print("The original message issued is:",original_msg) 

OUTPUT:

Signature

20131A1225 44
WEEK-1 21.03.2023

DIFFIE HELLMAN KEY EXCHANGE

Aim: To implement the DIFFIE HELLMAN KEY EXCHANGE technique or Algorithm.

Pre-Requisite:

Primitive root:
A primitive root of a prime p is an integer g such that g (mod p) has multiplicative
order p-1.

More generally, if GCD(g,n)=1 (g and n are relatively prime) and g is of multiplicative


order phi(n) modulo n where phi(n) is the totient function, then g is a primitive root of n.

In other words,

A primitive root of a prime number p is one whose powers modulo p generate all the integers
from 1 to p - 1. That is, if a is a primitive root of the prime number p, then the numbers
a mod p, a^2 mod p, … , a^(p-1) mod p
are distinct and consist of the integers from 1 through p - 1 in some permutation.

Introduction:
 The first published public-key algorithm appeared in the seminal paper by Diffie
and Hellman that defined public-key cryptography [DIFF76b].
 This is generally referred to as Diffie–Hellman key exchange.
 It is also known as EXPONENTIAL KEY EXCHANGE.
 This is a method for securely exchanging cryptographic keys over an insecure
channel.
 It is a fundamental building block of many secure communication protocols, including
SSL/TLS and SSH.
 A number of commercial products employ this key exchange technique.
 Its applications include:
1. VPN (Virtual Private Network)
2. FTPS (File transfer protocol)
3. VoIP (Voice over IP)
4. SCP (Security communication protocol)
 The purpose of the algorithm is to enable two users to securely exchange a key that
can then be used for subsequent symmetric encryption of messages.
 The algorithm itself is limited to the exchange of secret values.
 The Diffie–Hellman algorithm depends for its effectiveness on the difficulty of
computing discrete logarithms.

20131A1225 45
WEEK-1 21.03.2023

ALGORITHM:

The result is that the two sides have exchanged a secret value.

Proof:

20131A1225 46
WEEK-1 21.03.2023

Example:

Step 1: Alice and Bob get public numbers

P = 23, G = 9

Step 2: Alice selected a private key a = 4 and

         Bob selected a private key b = 3

Step 3: Alice and Bob compute public key values

Alice:   x =(94 mod 23) = (6561 mod 23) = 6

  Bob:    y = (93 mod 23) = (729 mod 23)   = 16

Step 4:  Alice and Bob exchange public numbers

Step 5:  Alice receives public key y =16       

              Bob receives public key x = 6

Step 6: Alice and Bob compute symmetric keys

             Alice:  ka = ya mod p = 65536 mod 23 = 9

             Bob:    kb = xbmod p = 216 mod 23 = 9

Step 7: 9 is the shared secret.

20131A1225 47
WEEK-1 21.03.2023

Execution:
import random
p=int(input("Enter a large prime number p:"))
q=int(input("Enter a primitive root of p (q<p):"))

#Generate private keys less than p
alice_pr=random.randint(1,p)
bob_pr=random.randint(1,p)

print("The randomly chosen Private Keys of Alice and Bob are:",alice_pr,bob_pr)

#Calculate public keys of both
alice_pu=pow(q,alice_pr)%p 
bob_pu=pow(q,bob_pr)%p
print("The generated public keys are:")
print("Alice's Public Key:",alice_pu)
print("Bob's Public Key:",bob_pu)

#Share the public keys and calculate the shared SECRET KEY
alice_secr_key=pow(bob_pu,alice_pr)%p
bob_secr_key=pow(alice_pu,bob_pr)%p
print("The Generated shared secret code:")
print("By Alice:",alice_secr_key)
print("By Bob:",bob_secr_key)

OUTPUT:

Signature

20131A1225 48
WEEK-1 28.03.2023

WIRESHARK
Aim: To demonstrate how to sniff for router traffic on a sample network using
WIRESHARK.

Pre-Requisite:
Wireshark is a free and open-source network protocol and traffic analyzer that can be
used to capture network traffic, troubleshoot networks and much more.
It is built-in in the Kali Linux.

KALI-LINUX:
It is a powerful tool for cybersecurity professionals and ethical hackers.
The number of tools configured and preinstalled on the operating system, make Kali
Linux the Swiss Army knife in any security professional’s toolbox.

Description:
WIRE-SHARK:
 Wireshark allows you to capture traffic on a network and presents the captured traffic
in the form of individual packets for granular analysis.
 Wireshark captures and dissects packets on a network and displays the various packet
fields and headers based on the  type of packet that was captured.
 Wireshark will not manipulate things on the network, it will only measure things
from it.

Features:

 Available for UNIX and Windows.


 Capture live packet data from a network interface.
 Open files containing packet data captured with tcpdump/WinDump, Wireshark, and
a number of other packet capture programs.
 Import packets from text files containing hex dumps of packet data.
 Display packets with very detailed protocol information.
 Save packet data captured.
 Export some or all packets in a number of capture file formats.
 Filter packets on many criteria.
 Search for packets on many criteria.
 Colorize packet display based on filters.
 Produce various statistics.

20131A1225 49
WEEK-1 28.03.2023

Purpose:
 Network administrators use it to troubleshoot network problems.
 Network security engineers use it to examine security problems.
 Developers use it to debug protocol implementations.
 People use it to learn network protocol internals.

PCAP Files:
 PCAP (Packet Capture) is an API that is used to capture and record network packets
from layer 2-7 of the OSI model.
 Wireshark utilizes the .pcap file format to capture and store packets for later analysis.
 Network traffic captured with Wireshark can be exported or imported in the form of
a .pcap file.
 This allows analysts to import and analyze network traffic that was captured on
another.

EXECUTION:

20131A1225 50
WEEK-1 28.03.2023
The whole working procedure is clearly shown in the images that follow
1. The packets are being captured once started.

2. Create a separate profile so as not to change the default settings.

20131A1225 51
WEEK-1 28.03.2023

3. On applying your profile, the packet capturing would look something like this.

4. Now let’s apply a Display Filter which would display only the packets satisfying the
given condition.

20131A1225 52
WEEK-1 28.03.2023

5. You can also apply Capture Filter as shown below

20131A1225 53
WEEK-1 28.03.2023

6. You can also get the data that you enter in a vulnerable website as shown below.

20131A1225 54
WEEK-1 28.03.2023

Signature

20131A1225 55
WEEK-1 28.03.2023

20131A1225 56
WEEK-1 04.04.2023

SECURE HASH ALGORITHM


Aim: To implement the Secure Hash Algorithm.
Pre-Requisite:

⮚ Secure Hash Algorithms, also known as SHA, are a family of cryptographic functions
designed to keep data secured. It works by transforming the data using a hash function: an
algorithm that consists of bitwise operations, modular additions, and compression
functions.
⮚ These algorithms are designed to be one-way functions, meaning that once they’re
transformed into their respective hash values, it’s virtually impossible to transform them
back into the original data.
⮚ A common application of SHA is to encrypting passwords, as the server side only needs
to keep track of a specific user’s hash value, rather than the actual password.

Description:
SHA-1:
A 160-bit hash function which resembles the earlier MD5 algorithm.
This was designed by the National Security Agency (NSA) to be part of the Digital
Signature Algorithm. Cryptographic weaknesses were discovered in SHA-1.
Mechanism:
Suppose the message ‘abc’ were to be encoded using SHA-1, with the message ‘abc’ in
binary being 01100001 01100010 01100011 and that in hex being 616263

Steps:

1. The first step is to initialize five random strings of hex characters that will serve as part of
the hash function (shown in hex):

H 0=67DE2A01
H1= BB03E28C
H2=011EF1DC
H3=9293E9E2
H4= CDEF23A9.

2. The message is then padded by appending a 1, followed by enough 0s until the message is


448 bits. The length of the message represented by 64 bits is then added to the end, producing
a message that is 512 bits long:

Padding of string "abc" in bits, finalized by the length of the string, which is 24 bits.

20131A1225 57
WEEK-1 04.04.2023
3. The padded input obtained above, M, is then divided into 512-bit chunks, and each chunk
is further divided into sixteen 32-bit words, W0…W15. In the case of ‘abc’, there’s only one
chunk, as the message is less than 512-bits total.

4. For each chunk, begin the 80 iterations, i, necessary for hashing (80 is the determined
number for SHA-1), and execute the following steps on each chunk,Mn:

For iterations 16 through 79, where 16≤i≤79, perform the following operation:

W(i)=S1(W(i−3)⊕W(i−8)⊕W(i−14)⊕W(i−16)) where XOR, or ⊕, is


represented by the following comparison of inputs x and y:

x y output

0 0 0

0 1 1

1 0 1

1 1 0

For example, when i is 16, the words chosen are W(13),W(8),W(2),W(0), and the output is
a new word, W(16), so performing the XOR, or ⊕, operation on those words will give
this:

W(0) 01100001 01100010 01100011 10000000

W(2) 00000000 00000000 00000000 00000000

W(8) 00000000 00000000 00000000 00000000

W(13) 00000000 00000000 00000000 00000000

W(16) 01100001 01100010 01100011 10000000

Circular Shift Operation

Now, the circular shift operation Sn(X) on the word X by n bits, n being an integer


between 0 and 32, is defined by

Sn(X)=(X<<n) OR (X>>32−n),

20131A1225 58
WEEK-1 04.04.2023
where X<<n is the left-shift operation, obtained by discarding the leftmost n bits of X and
padding the result with n zeroes on the right.

X>>32−n is the right-shift operation obtained by discarding the rightmost n bits of X and


padding the result with n zeroes on the left. Thus Sn(X) is equivalent to a circular shift
of X by n positions, and in this case the circular left-shift is used. 

So, a left shift Sn(W(i)), where W(i) is 10010 would produce 01001,as the rightmost bit 0 is


shifted to the left side of the string. Therefore, W(16) would end up being

11000010 11000100 11000111 000000000

5. Now, store the hash values defined in step 1 in the following variables:

A=H0
B=H1
C=H2
D=H3
E=H4.

6. For 80 iterations, where 0≤i≤79, compute TEMP=S5*(A)+f(i;B,C,D)+E+W(i)+K(i).


Reassign the following variables:
E=D
D=C
C=S30(B)
B= A
A=TEMP.
7. Store the result of the chunk’s hash to the overall hash value of all chunks, as shown
below, and proceed to execute the next chunk:

H0= H0 +A
H1=H1+B
H2=H2+C
H3=H3+D
H4=H4+E.

8. As a final step, when all the chunks have been processed, the message digest is represented
as the 160-bit string comprised of the OR logical operator, ∨, of the 5 hashed values:

HH=S128(H0) ∨ S96(H1) ∨ S64(H2) ∨ S32(H3) ∨ H4. So, the string ‘abc’ becomes


represented by a hash value akin to a9993e364706816aba3e25717850c26c9cd0d89d. If the

20131A1225 59
WEEK-1 04.04.2023
string changed to ‘abcd’, for instance, the hashed value would be drastically different so
attackers cannot tell that it is similar to the original message.

The hash value for 'abcd' is 81fe8bfe87576c3ecb22426f8e57847382917acf.

Execution:

def sha1(data):
    bytes = ""

    h0 = 0x67452301
    h1 = 0xEFCDAB89
    h2 = 0x98BADCFE
    h3 = 0x10325476
    h4 = 0xC3D2E1F0
for n in range(len(data)):
        bytes+='{0:08b}'.format(ord(data[n]))
    bits = bytes+"1"
    pBits = bits
    #pad until length equals 448 mod 512
    while len(pBits)%512 != 448:
        pBits+="0"
    #append the original length
    pBits+='{0:064b}'.format(len(bits)-1)

    def chunks(l, n):
        return [l[i:i+n] for i in range(0, len(l), n)]

    def rol(n, b):
        return ((n << b) | (n >> (32 - b))) & 0xffffffff

    for c in chunks(pBits, 512): 
        words = chunks(c, 32)
        w = [0]*80
        for n in range(0, 16):
            w[n] = int(words[n], 2)
        for i in range(16, 80):
            w[i] = rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)  

        a = h0
        b = h1
        c = h2
        d = h3
        e = h4

20131A1225 60
WEEK-1 04.04.2023

        #Main loop
        for i in range(0, 80):
            if 0 <= i <= 19:
                f = (b & c) | ((~b) & d)
                k = 0x5A827999
            elif 20 <= i <= 39:
                f = b ^ c ^ d
                k = 0x6ED9EBA1
            elif 40 <= i <= 59:
                f = (b & c) | (b & d) | (c & d) 
                k = 0x8F1BBCDC
            elif 60 <= i <= 79:
                f = b ^ c ^ d
                k = 0xCA62C1D6

            temp = rol(a, 5) + f + e + k + w[i] & 0xffffffff
            e = d
            d = c
            c = rol(b, 30)
            b = a
            a = temp

        h0 = h0 + a & 0xffffffff
        h1 = h1 + b & 0xffffffff
        h2 = h2 + c & 0xffffffff
        h3 = h3 + d & 0xffffffff
        h4 = h4 + e & 0xffffffff

    return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)
print(sha1("venkat sai krishna"))

Output:
b70c6c7bd378ccb0d3ff66b99734be6872cd4929

Signature

20131A1225 61
WEEK-1 11.04.2023

NIST Digital Signature


Aim: To implement the NIST Digital Signature Algorithm.
Pre-Requisite:

A good understanding of following is necessary for implementing the NIST DSA


effectively:
1. Public key cryptography
2. Secure random number generation
3. Hash functions
4. DSA parameters and
5. Key management

Description:

NIST DIGITAL SIGNATURE:

 The NIST DSA (Digital Signature Algorithm) is a widely used standard for
generating and verifying digital signatures.
 It is a public key cryptography algorithm, meaning it uses two keys – a private key
and a public key – to create and verify digital signatures.
 The private key is kept secret and is used to sign the message, while the public key is
distributed widely and is used to verify the signature.
 It requires the use of specific parameters such as prime numbers, generator values,
and key lengths.
 The algorithm uses a hash function to generate a fixed-length message digest, which
is then used as input for the digital signature algorithm.
 To generate a digital signature
 The sender first calculates a message digest of the message using a hash
function.
 The sender then generates a signature by computing a mathematical function
involving the private key, the message digest, and the DSA parameters.
 The resulting signature is then attached to the message and sent to the receiver.
 To verify a digital signature
 The receiver first calculates the message digest of the received message using
the same hash function used by the sender.
 The receiver then computes a mathematical function involving the public key,
the message digest, and the DSA parameters to verify the signature.
 If the signature is valid, the receiver can be confident that the message was
sent by the sender and has not been tampered with.

Algorithm:

20131A1225 62
WEEK-1 11.04.2023

Here is an overview of the steps involved in implementing the NIST DSA for generating and
verifying digital signatures:

Key Generation:
1. Choose a prime number p and a generator g, where p and (p-1)/2 are both prime
numbers. The values of p and g are fixed and standardized by the NIST.
2. Choose a random number x, 1 < x < p-1, as the private key.
3. Compute y = g^x mod p as the public key.

Signing:
4. Choose a random number k, 1 < k < p-1, where gcd(k, p-1) = 1. This value of k
should be different for each signature.
5. Compute r = (g^k mod p) mod q, where q is a prime divisor of p-1. The value of q is
also fixed and standardized by the NIST.
6. Compute s = (k^(-1) * (H(m) + xr)) mod q, where H(m) is the hash of the message m.
The value of s should be different for each signature.
The digital signature is (r, s).
Verification:
7. Verify that 0 < r < q and 0 < s < q. If either value is outside this range, the signature is
invalid.
8. Compute w = s^(-1) mod q.
9. Compute u1 = (H(m) * w) mod q and u2 = (r * w) mod q.
10. Compute v = ((g^u1 * y^u2) mod p) mod q.
11. The signature is valid if v = r. If v is not equal to r, the signature is invalid.

In addition to the steps outlined above, the implementation of the NIST DSA also includes
key management procedures to ensure the secure storage and distribution of private and
public keys.

Applications:

The NIST DSA algorithm is widely used for secure communication, digital
signatures, and authentication in various applications such as
1. e-commerce
2. online banking and
3. government systems.
The algorithm has been standardized by the National Institute of Standards and Technology
(NIST) and is recommended by many international standards organizations, including ISO
and IEC.

Execution:

20131A1225 63
WEEK-1 11.04.2023
!pip3 install Crypto
!pip3 install pycryptodome

from Crypto.Util.number import *
from random import *
from hashlib import sha1

# Hash of message in SHA1   
def hash_function(message):
    hashed=sha1(message.encode("UTF-8")).hexdigest()
    return hashed

# Modular Multiplicative Inverse
def mod_inverse(a, m) : 
    a=a%m; 
    for x in range(1,m) : 
        if((a*x)%m==1) : 
            return(x) 
    return(1)
# Global parameters are q,p, and g

def parameter_generation():

    # primes of 8 bits in length in binary
    # q is prime divisor
    q=getPrime(5)
    # p is prime modulus
    p=getPrime(10) 

    # Always p should be greater than q
    # because p-1 must be a multiple of q

    # to make sure that p not equal to q while generating randomly
    # and q is prime divisor of p-1
    while((p-1)%q!=0):
        p=getPrime(10)
        q=getPrime(5)

    print("Prime divisor (q): ",q)
    print("Prime modulus (p): ",p)

    flag=True
    while(flag):
        h=int(input("Enter integer between 1 and p-1(h): "))
        # h must be in between 1 and p-1
        if(1<h<(p-1)):
            g=1
            while(g==1):

20131A1225 64
WEEK-1 11.04.2023
                g=pow(h,int((p-1)/q))%p
            flag=False
        else:
            print("Wrong entry")
    print("Value of g is : ",g)
    
    # returning them as they are public globally
    return(p,q,g)

def per_user_key(p,q,g):
    
    # User private key:
    x=randint(1,q-1)
    print("Randomly chosen x(Private key) is: ",x)

    # User public key:
    y=pow(g,x)%p
    print("Randomly chosen y(Public key) is: ",y)

    # returning private and public components
    return(x,y)

def signature(name,p,q,g,x):
    with open(name) as file:
        text=file.read()
        hash_component = hash_function(text)
        print("Hash of document sent is: ",hash_component)
    r=0
    s=0
    while(s==0 or r==0):
        k=randint(1,q-1)
        r=((pow(g,k))%p)%q
        i=mod_inverse(k,q)

        # converting hexa decimal to binary
        hashed=int(hash_component,16)
        s=(i*(hashed+(x*r)))%q

    # returning the signature components
    return(r,s,k)

def verification(name,p,q,g,r,s,y):
    with open(name) as file:
        text=file.read()
        hash_component = hash_function(text)
        print("Hash of document received is: ",hash_component)

    # computing w

20131A1225 65
WEEK-1 11.04.2023
    w=mod_inverse(s,q)
    print("Value of w is : ",w)
    
    hashed=int(hash_component,16)

    # computing u1, u2 and v
    u1=(hashed*w)%q 
    u2=(r*w)%q
    v=((pow(g,u1)*pow(y,u2))%p)%q
    
    print("Value of u1 is: ",u1)
    print("Value of u2 is: ",u2)
    print("Value of v is : ",v)

    if(v==r):
        print("The signature is valid!")
    else:
        print("The signature is invalid!")

from google.colab import drive
drive.mount('/content/drive/')

%cd /content/drive/My Drive/Colab Notebooks/

global_var=parameter_generation()
keys=per_user_key(global_var[0],global_var[1],global_var[2])

# Sender's side (signing the document):
print()
file_name=input("Enter the name of document to sign: ")
components=signature(file_name,global_var[0],global_var[1],global_var[2
],keys[0])

print("r(Component of signature) is: ",components[0])
print("k(Randomly chosen number) is: ",components[2])
print("s(Component of signature) is: ",components[1])

# Receiver's side (verifying the sign):
print()
file_name=input("Enter the name of document to verify: ")
verification(file_name,global_var[0],global_var[1],global_var[2],compon
ents[0],components[1],keys[1])

OUTPUT:

20131A1225 66
WEEK-1 11.04.2023

Signature

20131A1225 67
WEEK-1 11.04.2023

NMAP- Network Mapper


Aim: To Verify vulnerabilities, test known exploits using the tool N-Map.
Pre-Requisite:
 Kali Linux comes with Nmap pre-installed as part of its standard toolset.
 Kali Linux is a specialized Linux distribution designed specifically for penetration
testing, ethical hacking, and network security assessments, and Nmap is a popular tool
in this domain.
 In Kali Linux, you can use Nmap from the command line by opening a terminal
window and typing nmap followed by the desired command-line options and
arguments.
 Nmap is an essential tool for network security assessments, and its inclusion in Kali
Linux makes it a popular choice for penetration testers and security professionals.

Description:

N-MAP:

 Nmap (short for Network Mapper) is a powerful and versatile open-source tool for
network exploration, security scanning, and port and service enumeration.
 It was originally created by Gordon Lyon (also known by his pseudonym Fyodor
Vaskovich) and first released in 1997.
 Nmap is designed to help security professionals, system administrators, and other
users to discover and map out networks, identify hosts and devices connected to them,
and detect open ports and services running on those hosts.
 It can also perform vulnerability scanning, OS and version detection, and many other
network analysis tasks.
 One of the key features of Nmap is its ability to perform fast and accurate port
scanning on large networks, using a variety of scanning techniques such as TCP SYN
scanning, TCP connect scanning, UDP scanning, and others.
 It also includes advanced features such as OS detection, traceroute functionality, and
scripting capabilities that allow users to create custom scan scripts and automate
complex tasks.

Key-Functionalities:
Some of its key functionalities include:
1. Port scanning: Nmap can perform fast and accurate port scanning on large networks,
using a variety of scanning techniques such as TCP SYN scanning, TCP connect
scanning, UDP scanning, and others.
2. Host and device discovery: Nmap can detect and identify hosts and devices
connected to a network, and provide information such as IP addresses, MAC
addresses, and operating systems.

20131A1225 68
WEEK-1 11.04.2023
3. Service and version detection: Nmap can identify the services running on open
ports, and detect their version numbers and other characteristics.

4. Operating system detection: Nmap can identify the operating system of a host or
device based on its network responses.
5. Scripting: Nmap has a powerful scripting engine that allows users to create custom
scan scripts and automate complex tasks.
6. Traceroute: Nmap can perform traceroute-like functionality to identify the path taken
by packets through the network.
7. Vulnerability scanning: Nmap can detect known vulnerabilities in services and
applications running on open ports, using its built-in database of vulnerability
information.
8. Output customization: Nmap provides a wide range of output options and formats,
allowing users to customize the output of their scans for further analysis.

EXECUTION:
1. Syntax for Scanning a Single IP:

nmap <ip address>

20131A1225 69
WEEK-1 11.04.2023

2. Syntax for Scanning a Single Port:


nmap -p <port number><IP address>

3. Syntax for Scanning 100 Most Common Ports:


nmap -f <IP address>

20131A1225 70
WEEK-1 11.04.2023

4. nmap for scanning a host:

sudo nmap www.gvpce.ac.in

20131A1225 71
WEEK-1 11.04.2023

Some other Nmap Commands:

20131A1225 72
WEEK-1 11.04.2023

Signature

20131A1225 73
WEEK-1 18.04.2023

Phishing Attacks
Aim: To Simulate and test real-world phishing attacks.
Pre-Requisite:
Phishing attacks are a form of social engineering where attackers attempt to trick individuals
into divulging sensitive information such as passwords, credit card details, or personal
information.
These attacks can take many forms, including email phishing, phone phishing, or SMS
phishing.

We simulate these attacks using Kali-Linux.


Execution:
We go to the SOCIAL ENGINEERING TOOLKIT where we get to do these attacks.
WEBSITE CLONER
1. There we choose Social Engineering Attacks.

2. Then we choose the WebSite attack Vectors.

20131A1225 74
WEEK-1 18.04.2023
3. Then we choose Credential Harvester Attack Method.

4. Then opt for WebSite Cloner.

5. Then it asks to enter IP address which is already visible just to the left.Enter it and
later provide the target url.

20131A1225 75
WEEK-1 18.04.2023
OUTPUT:
Type the generated ip address in the WebBrowser

Retrieving UserName & Password:


1. Instead of Website Cloner , choose WebTemplates

2. Enter the IP Address as mentioned earlier.

20131A1225 76
WEEK-1 18.04.2023
3. Choose Google to Proceed

4. When you enter the IP Address in the Browser, you will be asked to login to ur
Google Account .

5. Then Your details are obtained in the Tool as shown below:

20131A1225 77
WEEK-1 18.04.2023

Phishing Mail Attack


Each step is detailed in the pictures itself.

20131A1225 78
WEEK-1 18.04.2023

Here Log in to your Gmail account. In Security, go to APP PASSWORDS

20131A1225 79
WEEK-1 18.04.2023

OUTPUT:

Signature

20131A1225 80
WEEK-1 18.04.2023

INTRUSION DETECTION USING SNORT

Aim: To demonstrate the intrusion detection system using SNORT tool.


Pre-Requisites:
Snort has to be installed on your Linux Platform either Ubuntu or Kali Linux.

Demonstration:
You can check your version using:

snort –version

Configuring Snort

There are a few steps to complete before we can run Snort. We need to edit the “snort.conf”
file.
sudo gedit /etc/snort/snort.conf

Locate the line that reads “ipvar HOME_NET any” and edit it to replace the “any” with the
CIDR notation address range of your network.

20131A1225 81
WEEK-1 18.04.2023
Download the rule set for the version of Snort you’ve installed.

Once the download is complete, use this command to extract the rules and install them in the
“/etc/snort/rules” directory.

sudo tar -xvzf snortrules-snapshot-2983.tar.gc -C /etc/snort/rules

Promiscuous Mode:

Network interface cards usually ignore traffic that isn’t destined for their IP address. We want

Snort to detect suspicious network traffic addressed to any device on the network, not just

network traffic that happens to be sent to the computer on which Snort is installed.

To make the Snort computer’s network interface listen to all network traffic, we need to set it

to promiscuous mode. The following command will cause network interface enp0s3 to

operate in promiscuous mode. Substitute enp0s3 with the name of the network interface you

are using on your computer.

sudo ip link set enp0s3 promisc on

Running Snort

You can now start Snort. The command format is:


sudo snort -d -l /var/log/snort/ -h 192.168.1.0/24 -A console -c /etc/snort/snort.con

20131A1225 82
WEEK-1 18.04.2023

The command-line options used in this command are:


-d: Filters out the application layer packets.
-l /var/log/snort/: Sets the logging directory.
-h 192.168.1.0/24: This doesn’t set the home network, that was set in the “snort.conf” file.
With this value set to the same value as the home network, the logs are structured so that
content from suspicious remote computers is logged into directories named after each remote
computer.
-A console: Sends alerts to the console window.
-c /etc/snort/snort.conf: Indicates which Snort configuration file to use.
Snort scrolls a lot of output in the terminal window, then enters its monitoring an analysis
mode. Unless it sees some suspicious activity, you won’t see any more screen output.

From another computer, we started to generate malicious activity that was directly aimed at
our test computer, which was running Snort.

20131A1225 83
WEEK-1 18.04.2023

Attacks classified as “Information Leaks” attacks indicate an attempt has been made to
interrogate your computer for some information that could aid an attacker. This probably
indicates that someone is performing reconnaissance on your system.
Attacks classified as “Denial of Service” attacks indicate an attempt to flood your computer
with false network traffic. The attack tries to overwhelm your computer to the point that it
cannot continue to provide its services.
To verify that promiscuous mode is operating correctly and we’re safeguarding the entire
network address range, we’ll fire some malicious traffic at a different computer, and see
whether Snort detects it.

The activity is detected and reported, and we can see that this attack was directed against a
different computer with an IP address of 192.168.1.26. Snort is monitoring the entire address
range of this network.

Signature

20131A1225 84
WEEK-1 18.04.2023

ADDITIONAL
EXPERIMENTS

20131A1225 85
WEEK-1 25.04.2023

PLAY FAIR CIPHER


Aim: To implement the Play Fair Cipher Algorithm.
Pre-Requisite:
 The Playfair cipher technique is a classical symmetric cryptographic technique that uses a
polygraphic substitution method for encrypting text.
 It belongs to the category of substitution ciphers, which means that it replaces plaintext
characters with ciphertext characters based on a specific algorithm or key.

Description:

Play Fair Cipher Technique:

The Playfair cipher technique is a cryptographic technique that uses a polygraphic


substitution method for encrypting text.
It was invented in 1854 by Charles Wheatstone but was later popularized by Lord Playfair.
The following is the implementation of the Playfair cipher technique:
Key Phrase:
The Playfair cipher requires a key phrase or keyword to encrypt and decrypt the
text. The key phrase should be easy to remember, and it is used to generate a 5x5 matrix. This
matrix is used for the encryption and decryption of the plaintext.
Removing Duplicates and Spaces:
The Playfair cipher works with a 5x5 matrix of letters, and there can't be any
duplicates. The matrix should contain all 26 letters of the alphabet, excluding the letter 'J'.
Spaces and punctuation marks are removed from the plaintext before encryption.
Padding:
If the plaintext has an odd number of characters, a padding character (such as 'X') is
added to the end of the text to make it an even number of characters.
Break Plaintext into Pairs:
The plaintext is then broken into pairs of two letters. If there is a repeated letter in a
pair, a padding character is added between them. For example, 'hello' would become 'HE LX
LO'.
Encryption/Decryption:
Finally, the ciphertext is generated using the 5x5 matrix and the pairs of letters. The
decryption process uses the same matrix to translate the ciphertext back to plaintext.

20131A1225 86
WEEK-1 25.04.2023

Execution:
def create_matrix(key):
    key = key.upper()
    matrix = [[0 for i in range (5)] for j in range(5)]
    letters_added = []
    row = 0
    col = 0
    # add the key to the matrix
    for letter in key:
        if letter not in letters_added:
            letters_added.append(letter)
        else:
            continue
    #Add the rest of the alphabet to the matrix
    # A=65 ... Z=90
    for letter in range(65,91):
        if letter==74: # I/J are in the same position
                continue
        if chr(letter) not in letters_added: # Do not add repeated lett
ers
            letters_added.append(chr(letter))
            
    #print (len(letters_added), letters_added)
    index = 0
    for i in range(5):
        for j in range(5):
            matrix[i][j] = letters_added[index]
            index+=1
    return matrix
key=input("Enter the key : ")
message=input("Enter the message : ")
def separate_same_letters(message):
    index = 0
    while (index<len(message)-1):
        l1 = message[index]
        l2 = message[index+1]
        if l1==l2:
            message = message[:index+1] + "X" + message[index+1:]
        index +=2   
    if(len(message)%2!=0):
      message+="Z"
    return message
print(separate_same_letters(message))
def indexOf(letter,matrix):
    for i in range (5):
        try:
            index = matrix[i].index(letter)
            return (i,index)

20131A1225 87
WEEK-1 25.04.2023
        except:
            continue
def playfair(key, message, encrypt=True):
    inc = 1
    if encrypt==False:
        inc = -1
    matrix = create_matrix(key)
    print("Matrix formed is : ",matrix)
    message = message.upper()
    message = message.replace(' ','')    
    message = separate_same_letters(message)
    print("Message is : ",message)
    cipher_text=''
    for (l1, l2) in zip(message[0::2], message[1::2]):
        row1,col1 = indexOf(l1,matrix)
        row2,col2 = indexOf(l2,matrix)
        if row1==row2: #Rule 2, the letters are in the same row
            cipher_text += matrix[row1][(col1+inc)%5] + matrix[row2]
[(col2+inc)%5]
        elif col1==col2:# Rule 3, the letters are in the same column
            cipher_text += matrix[(row1+inc)%5][col1] + matrix[(row2+in
c)%5][col2]
        else: #Rule 4, the letters are in a different row and column
            cipher_text += matrix[row1][col2] + matrix[row2][col1]
    
    return cipher_text
Cipher=playfair(key,message)
print("Cipher text : ",Cipher)
print("Plain text: ",playfair(key,Cipher,False))

OUTPUT:

Signature

20131A1225 88
WEEK-1 25.04.2023

MD5 ALGORITHM
Aim: To implement the MD5 Algorithm.
Description:

MD5 (Message-Digest Algorithm 5) is a widely-used cryptographic hash function that


produces a 128-bit hash value. It was invented by Ron Rivest in 1991, as a successor to the
earlier MD4 hash function.

The purpose of a hash function is to take an input of any length (referred to as the "message")
and produce a fixed-length output (the "hash" or "digest") that serves as a unique
representation of the input. Hash functions are widely used in cryptography and data integrity
applications to ensure that data has not been tampered with or altered.

The MD5 algorithm takes as input a message of any length and produces a 128-bit hash
value. It does this by processing the message in 512-bit blocks and performing a series of
bitwise and logical operations on each block. The resulting hash value is unique to the input
message and serves as a digital fingerprint of the message's contents.

Code:
# helper function to perform left circular shift on a 32-bit integer
def left_circular_shift(x, n):
return ((x << n) | (x >> (32 - n))) & 0xffffffff

# initial state for MD5 algorithm (four 32-bit words)


a = 0x67452301
b = 0xefcdab89
c = 0x98badcfe
d = 0x10325476

# message to hash
message = "Hello, world!"

# pad the message to a multiple of 64 bytes (512 bits)


message_bytes = message.encode()
message_len = len(message_bytes)
padding_len = (64 - (message_len + 8) % 64) % 64
padding = b'\x80' + (b'\x00' * padding_len)
message = message_bytes + padding + message_len.to_bytes(8, byteorder='little')

# process the message in 512-bit blocks


for i in range(0, len(message), 64):
# extract a 16-word block from the message

20131A1225 89
WEEK-1 25.04.2023
block = message[i:i+64]
words = [int.from_bytes(block[j:j+4], byteorder='little') for j in range(0, 64, 4)]

# save the initial state for this block


aa, bb, cc, dd = a, b, c, d

# perform four rounds of hashing on this block


for j in range(64):
if j < 16:
f = (b & c) | ((~b) & d)
g=j
elif j < 32:
f = (d & b) | ((~d) & c)
g = (5*j + 1) % 16
elif j < 48:
f=b^c^d
g = (3*j + 5) % 16
else:
f = c ^ (b | (~d))
g = (7*j) % 16

temp = d
d=c
c=b
b = b + left_circular_shift((a + f + words[g] + 0x5a827999), 5)
a = temp

# update the state for the next block


a = (a + aa) & 0xffffffff
b = (b + bb) & 0xffffffff
c = (c + cc) & 0xffffffff
d = (d + dd) & 0xffffffff

# concatenate the final state values to get the hash


hash_value = (a.to_bytes(4, byteorder='little') +
b.to_bytes(4, byteorder='little') +
c.to_bytes(4, byteorder='little') +
d.to_bytes(4, byteorder='little'))

# convert the hash value to a hexadecimal string


hash_hex = ''.join(format(b, '02x') for b in hash_value)

# print the hash value


print("MD5 hash value of {}: {}".format(message_bytes.decode(), hash_hex))

20131A1225 90
WEEK-1 25.04.2023

OUTPUT:

Signature

20131A1225 91

You might also like