Implementation of Playfair Cipher in Python

Playfair Cipher is a digraph substitution cipher where a 5×5 matrix of alphabets is created according to the key. It is a symmetric cipher where there is only one key for encryption and decryption.

Example 1:

Message: IAMLEARNING

Key: KIDSLABZ

We have to split the message by pairing two characters: IA, ML, EA, RN, IN, GX [X is added as only 1 character remains]

5×5 matrix according to the key:

In this matrix, character ‘J’ is omitted; instead, it is replaced by character ‘I’.

Encryption:

Take character pair from splitted message and check the position of each character in the 5×5 matrix.

If the characters lie in the same row, then the encrypted message will be one character right from both characters. [Move to the left, if the character is in the rightmost column]

If the characters lie in the same column, then the encrypted message will be one character below both characters. [Move to the top, if the character is in the bottommost row]

If the characters lie in different rows and columns, the encrypted message will be the horizontal opposite corner of the rectangle formed by the two characters.

IA = They lie in different rows and columns, so the encrypted message will be KB

ML = They lie in different rows and columns, so the encrypted message will be NS

EA = They lie on the same row, so the encrypted message will be AB

RN = They lie in different rows and columns, so the encrypted message will be TM

IN = They lie in different rows and columns, so the encrypted message will be LG

GX = They lie in different rows and columns, so the encrypted message will be MV

Final encrypted message = KBNSABTMLGMV

 

Example 2:

Message: PROGRAMMING

Splitted Message: PR, OG, RA, MX [X is added because pair cannot be made with the same letter ], MI, NG

Encryption:

PR = They lie on the same row, so the encrypted message will be QT

OG = They lie in different rows and columns, so the encrypted message will be PF

RA = They lie in different rows and columns, so the encrypted message will be OC

MX = They lie on the same column, so the encrypted message will be RS

MI = They lie in different rows and columns, so the encrypted message will be GS

NG = They lie on the same row, so the encrypted message will be FH

Final encrypted message: QTPFOCRSGSFH

The implementation of the Playfair Cipher in Python is given below:

# Python program to implement Playfair Cipher

message = "IAMLEARNING"
# message = "PROGRAMMING"
key = "KIDSLABZ"
new_message = ""

splitted_msg = []
matrix = []
encrypted_msg = ""

# Function to split the message and group into 2 characters
def split_message():
	global new_message
	# Checking if there is any similar characters adjacent to each other and generate new message
	for i in range(0, len(message), 2):
		# Checking for single character remaining
		if len(message[i:i+2]) < 2:
			new_message = new_message + message[i]
		elif message[i] == message[i+1]:
			new_message = new_message + message[i] + "X" + message[i+1]
		else:
			new_message = new_message + message[i] + message[i+1]

	# Splitting the new message
	for i in range(0, len(new_message), 2):
		temp = new_message[i:i+2]
		if len(temp) < 2:
			temp += "X"
		splitted_msg.append(temp)


# Function to generate the 5x5 matrix
def generate_matrix():
	checked_char = key
	for i in range(5):
		row = []
		for j in range(5):
			# Adding characters of key into the matrix
			if 5*i+j < len(key):
				row.append(key[5*i+j])
			else:
				# Adding other alphabets into the matrix
				for k in range(65, 91):
					if chr(k) not in checked_char:
						if chr(k) == 'J':
							continue
						row.append(chr(k))
						checked_char += chr(k)
						break
		matrix.append(row)


# Function to get location of character in the matrix
def getLocation(c):
	for i in range(5):
		for j in range(5):
			if matrix[i][j] == c:
				return i,j

# Function to generate encrypted characters	
def encryption(x1,y1,x2,y2):
	char1 = ""
	char2 = ""
	# If the characters lies in the same row
	if x1 == x2:
		char1 = matrix[x1][(y1 + 1)%5]
		char2 = matrix[x2][(y2 + 1)%5]
	# If the characters lies in the same column
	elif y1 == y2:
		char1 = matrix[(x1 + 1)%5][y1]
		char2 = matrix[(x2 + 1)%5][y2]
	# If the characters lies in the different row and column
	else:
		char1 = matrix[x1][y2]
		char2 = matrix[x2][y1]
	return char1, char2


# Calling the functions to split message and generate matrix
split_message()
generate_matrix()

# Finding the locations of characters from splitted message and generate encrypted characters
for i in range(len(splitted_msg)):
	x1, y1 = getLocation(splitted_msg[i][0])
	x2, y2 = getLocation(splitted_msg[i][1])

	char1, char2 = encryption(x1, y1, x2, y2)
	encrypted_msg = encrypted_msg + char1 + char2

# Printing the data
print("Message: ", message)
print("New Message: ", new_message)
print("Splitted Message: ", splitted_msg)
print("Key: ", key)
print("Generated Matrix: ")
for i in range(5):
	print(matrix[i])
print("Encrypted Message: ", encrypted_msg)
Continue reading “Implementation of Playfair Cipher in Python”

Implementation of Vigenère Cipher in Python

Vigenère cipher is a polyalphabetic substitution cipher where a series of alphabets are used as key for encryption.  Each character in the plaintext is shifted with respect to the corresponding character of the key to generate encrypted text. It is also a type of block cipher.

Example 1:

Plain Text: VIGENEREC

Key: SAMPLEKEY

Encryption: Plain Text + Key

= V + S

= 21 + 18

= 39 % 26 [mod 26, if in case, sum > 26]

= 13

= N

Cipher Text: NISTYIBIA

Decryption: Cipher Text – Key

= N – S

= 13 – 18

= -5 + 26 % 26 [+26, if in case, difference < 0, and mod 26, if in case, sum > 26]

=  21

= V

If the length of plaintext is greater than that of key, key generation need to perform for the program.

Example 2:

Plain Text: THISISASAMPLEPLAINTEXT

Key: SAMPLEKEY

Generated Key: SAMPLEKEYSAMPLEKEYSAMP

Cipher Text: LHUHTWKWYEPXTAPKMLLEJI

# Implementation of Vegenere Cipher in python

plaintext = "VIGENEREC"
key = "SAMPLEKEY"
keygen = key
ciphertext = ""
decryptedtext = ""

# Key Generation for inequal length of plaintext and key
# Key is repeated until its length is equal to that of plaintext and store in keygen
if len(plaintext) > len(key):
	for i in range(len(plaintext) - len(key)):
		keygen = keygen + key[i%len(key)]

# Encryption
for i in range(len(plaintext)):
	px = ord(plaintext[i]) - ord('A')
	kx = ord(keygen[i]) - ord('A')
	cx = (px + kx) % 26
	ciphertext = ciphertext + chr(cx + ord('A'))


print('Plain Text: ', plaintext)
print('Key: ', key)
print('Generated Key: ', keygen)
print('Cipher Text:', ciphertext)

# Decryption
for i in range(len(ciphertext)):
	cx = ord(ciphertext[i]) - ord('A')
	kx = ord(keygen[i]) - ord('A')
	px = (cx - kx + 26) % 26
	decryptedtext = decryptedtext + chr(px + ord('A'))

print('Decrypted Text: ', decryptedtext)
Continue reading “Implementation of Vigenère Cipher in Python”

Python program to calculate the percentage of marks of students using functions

Here is a python program to calculate the percentage of marks of students and display the student who got the highest and the lowest percentage using functions. Use the following table for the marks of students. And the Full Mark of each subject is 100.

Here is the program:

# Python program to calculate percentage of student marks and find the student with highest and lowest percentage using function

# Storing the list of students
students = ["Ironman", "Spiderman", "Superman", "Aquaman", "Batman"]
# Storing the list of subjects
subjects = ["Science", "Social science", "Moral science", "Computer science", "Home science"]
# Storing the marks of each students in different lists
marks1 = [95, 80, 76, 91, 59]
marks2 = [83, 91, 62, 79, 69]
marks3 = [70, 72, 81, 53, 63]
marks4 = [40, 65, 90, 45, 80]
marks5 = [90, 85, 70, 96, 50]

# Function to display the elements in a list
def display_list(list):
	for i in range(len(list)-1):
		print(list[i], end=", ")
	print(list[len(list)-1])

# Function to calculate the percentage from marks
def find_percentage(marks):
	total = 0
	for i in range(len(marks)):
		total += marks[i]
	percent = (total/500)*100

	return round(percent,2)

# Declare a percentage list to store percentage of each students
percentage = []

# Calculate percentage of each students and store in percentage list
def calculate_all_percentage():
	percent1 = find_percentage(marks1)
	percentage.append(percent1)
	percent2 = find_percentage(marks2)
	percentage.append(percent2)
	percent3 = find_percentage(marks3)
	percentage.append(percent3)
	percent4 = find_percentage(marks4)
	percentage.append(percent4)
	percent5 = find_percentage(marks5)
	percentage.append(percent5)

# Function to find the highest and lowest percentage and display the student
def find_highest_and_lowest():
	high = 0
	low = 0
	for i in range(len(percentage)):
		if percentage[high] < percentage[i]:
			high = i

	for j in range(len(percentage)):
		if percentage[low] > percentage[j]:
			low = j
	print("Student with highest percentage = ", students[high])
	print("Student with lowest percentage = ", students[low])

# Printing the list of students
print("List of students: ", end="")
display_list(students)

# Printing the list of subjects
print("List of subjects: ", end="")
display_list(subjects)

# Calling function to calculate percentages
calculate_all_percentage()

# Printing the list of percentages
print("Percentage of each students: ", end="")
display_list(percentage)

# Calling function to find student with highest and lowest percentage
find_highest_and_lowest()
Continue reading “Python program to calculate the percentage of marks of students using functions”

How to count inversions in an array?

Counting inversions is the total number of movements in an array to reach the final sorted array.

Let us take an example to count the inversions in an array:

Array = [9, 7, 10, 2, 4, 5]

In this array, the elements are not in sorted order, so some elements need to rearrange to be in the sorted order. For sorted array, there is 0 inversions.

Let us take the first element ‘9’ and start comparing with other remaining elements.

(9,7) – Not sorted

(9, 10) – Sorted

(9, 2) – Not sorted

(9, 4) – Not sorted

(9, 5) – Not sorted

For ‘9’, the inversions = 4 (number of not sorted)

Just like above, we will continue for next element ‘7’.

For ‘7’, the inversions = 3 [(7, 2), (7, 4), (7, 5)]

For next element ’10’, the inversions = 3 [(10, 2), (10, 4), (10, 5)]

For next element ‘2’, the inversions = 0 (all pairs are sorted)

For next element ‘4’, the inversions = 0

For next element ‘5’, the inversions = 0

Hence the total inversions of the array = 4 + 3 + 3 + 0 + 0 + 0 = 10.

In this way, we can count the number of inversions in an array whether the array is to sort in ascending order or in descending order.

Counting the number of additions in finding fibonacci series using recursive function in Python

Hello Friends,

Here is the python3 code to count the number of additions in finding fibonacci series using recursive function.

Fibonacci Series: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ……..

Solving fibonacci(6) and finding the number of additions.

In the above diagram, a recursion tree is drawn and the leaf node becomes f(1) and f(0).

Number of f(1) = 8 and number of f(0) = 5.

Total = 8 + 5 = 13 leaf nodes.

To add n numbers, n-1 number of addition operation will perform.

So to get the value at position 6, we need to add 13 numbers, it means 12 times addition operation will perform.

Another method to get the value at position 6 is to find the number of f(1) in the recursion tree, it means the value is 8.

#Python program to count the number of additions in recursive fibonacci

#Declare global variable to count
times = 0
# Defining the fibonacci function
def fibonacci(num):
	global times
	if num <= 1:
		return num
	#Incrementing the times variable
	times = times+1;
	return fibonacci(num-1) + fibonacci(num-2)

#Getting value from the user
num = int(input('Enter the position: '))
#Printing the value of series in the entered position
print('Value: ',fibonacci(num))
#Printing the number of additions
print('Number of additions: ',times)

Output of the above code:

Thank you

Implementation of Horner’s rule in C

Hello Friends,

Horner’s rule is a way to evaluate a polynomial expression by reducing the time complexity.

Let us take an example:

2x^3 + 3x^2 + 4x + 5

The above expression can also be represented as

((2 * x + 3) * x + 4) * 5

This is horner’s rule.

Here is the C program:

#include<stdio.h>
#include<conio.h>
void main() {
	int degree,x;
	int coeff[10], i;
	int sum = 0;
	
	// Getting the degreee of the polynomial
	printf("\nEnter the degree of the polynomial: ");
	scanf("%d",&degree);
	
	// Getting the coefficients of all terms of the polynomial
	printf("\nEnter the coeffients from lower order to higher order: \n");
	for(i=0; i<=degree; i++) {
		scanf("%d",&coeff[i]);
	}
	
	// Getting the value of the variable
	printf("\nEnter the value of x: ");
	scanf("%d",&x);

	// Applying Horner's rule
	sum = coeff[degree];
	for(i=degree-1; i>=0; i--) {
		sum = sum*x + coeff[i];
	}
	
	// Printing result
	printf("\nResult: %d",sum);
	getch();
}

Output of the above code.

Solving the above polynomial by using x = 2.

Thank you.

Simple Calculator of 2 numbers in Visual Basic

Design View of the Calculator

Visual Basic is a part of Visual Studio, so Visual Studio is used to write a program of visual basic. This calculator contains 2 textboxes to get input from the user, 4 buttons to perform 4 arithmetic operations (Addition, Subtraction, Multiplication, Division), and some labels.

Some conditions that is applied in this calculator are:

  1. If the user clicks any button for any operation without entering any values in the textboxes, it will give a warning message.
  2. While performing division, if the user enters 0 in Number 2, it will give a warning message because dividing any number by 0 is invalid.

Below is the VB code.

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text = "" Or TextBox2.Text = "" Then
            Label5.Text = "Please enter the values !"
        Else
            Dim num1, num2 As Integer
            num1 = TextBox1.Text
            num2 = TextBox2.Text
            Label5.Text = "Sum: " & num1 + num2
        End If

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        If TextBox1.Text = "" Or TextBox2.Text = "" Then
            Label5.Text = "Please enter the values !"
        Else
            Dim num1, num2 As Integer
            num1 = TextBox1.Text
            num2 = TextBox2.Text
            Label5.Text = "Difference: " & num1 - num2
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        If TextBox1.Text = "" Or TextBox2.Text = "" Then
            Label5.Text = "Please enter the values !"
        Else
            Dim num1, num2 As Integer
            num1 = TextBox1.Text
            num2 = TextBox2.Text
            Label5.Text = "Product: " & num1 * num2
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        If TextBox1.Text = "" Or TextBox2.Text = "" Then
            Label5.Text = "Please enter the values !"
        Else
            Dim num1, num2 As Integer
            num1 = TextBox1.Text
            num2 = TextBox2.Text
            If num2 = 0 Then
                Label5.Text = "Divisor cannot be 0 !"
            Else
                Label5.Text = "Division: " & num1 / num2
            End If
        End If
    End Sub
End Class

Thank you

Generate SHA 256 hashing using Python 3

Hello Friends,

SHA 256 is a Secure Hash Algorithm that generates 256 bit signature of the string. This hashing algorithm generates fixed size of hash for any length of input string. This is a one-way function so the result that is generated from this algorithm cannot be decrypted back.

This algorithm is also used in Blockchain to secure the data.

# Generating SHA hashing using Python 3
# Import sha256 module from hashlib
from hashlib import sha256

# Getting input string from the user
your_data = input('Enter a string: ')

# Generating SHA256 hash
hash_result = sha256(str(your_data).encode())
result = hash_result.hexdigest()

# Printing the result
print('Result: ',str(result))

Output of the above code:

Result of the above code

Thank you

Weka – Data Mining Tool

Friends,

Weka is a Data Mining with Open Source Machine Learning Software in Java. This contains tools for data preparation, classification, regression, clustering, association rules mining, and visualization. This software is open source software issued under the GNU General Public License.

You can download the software from here.

You can also learn how to work with weka from YouTube.

Thank you