Cryptography Code To Encrypt String In Python (2024)

History of Cryptography

The word “Krypto” means “hidden” and “Graphene” means “writing”. So, the word means “hidden writing”. The art of Cryptography can be traced back to as old as the Roman and Egyptian civilizations. The Egyptians would use hieroglyph codes to send secret messages on behalf of their kings. During World War, Morse Code ciphers were used by Germany and US to send their secret messages.

What is Cryptography?

Cryptographyis a technique of securing information and communications through the use of codes so that only those people for whom the information is intended can understand it and process it. Thus, preventing unauthorized access to information. One of the techniques to encrypt the text is to replace the original letters with letters using some set pattern which as a result encrypts the text.

Coding enhances problem-solving skills while making our life easier. At Skoolofcode, students use Python as a programming language for cryptography, making things easier for those who wanted to hide the original text. It was not only less time-consuming but also more efficient. Cryptography with Python is a simple code and you can easily do it with your kids. Let’s see how it’s done.

Algorithm for Cryptography with Python

Build the program where user-entered text is encrypted with python.

  1. Make a list of all the alphabet.
  2. Create a function that takes the text and a number as a parameter.
  3. Move through each element.
  4. If it’s a space add it to the new list as it is.
  5. Take out the position of the character it should replace with.
  6. Join.
  7. Display the encrypted text.

Code for Cryptography with Python

Now that we understand the algorithm. Let’s code to encrypt text with python.

Let’s make a list of all letters.

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

Create a variable with space

playing = ''

It’s now time to define the function with parameters

def encrypt(str, n):

Create a new empty list inside the function.

result = [ ]

To move through the text element by element, we would use for loop.

for x in str:

We would now need to check if the element is space. If it is a space then append the result list as it is.

if x == " ": converted = " " result.append(converted)

else we shall calculate the position of the character that we should replace with the original text and then append the result list. index() is an inbuilt function in Python, whichsearches for a given element from the start of the list and returns the lowest index where the element appears.For example, there is a list of fruits= [“banana”, “strawberry”, ”cherry]. We want to know the position of the cherry. In this case we can write: y=fruits. index(“cherry”). If I print the value of y here I would get 2. Which is the index value of cherry.

We would use this function and pass the element in x and look for the position in the letters list, that is letters. index(x). We are further adding the number entered by the user to this index. Therefore, we get the index of the character that should replace the element.(letters.index(x) + n). Now, this would work fine until the number is so added that the index goes out of the range. Say for example the original text had the element x and the number added is 3. The original index of x is 24 when 3 is added it makes it 27. Index 27 is not in the letters list and would give us an error. Also, we want that in such a case x should be replaced by a. Thus, we would use modules and save it as the converted variable.

converted = (letters.index(x) + n) % 26

Next, is to append the result list using the new index. Code shall be-

else: converted = (letters.index(x) + n) % 26 result.append(letters[converted])

Picking up letters of the mentioned positions from the result list to the final text and printing it.

final = ''.join(result) print(final)

Now, that we have created the function. We will ask for the input of the text that we should encrypt with python. Also, ask for the number of the shift in letters that the user wants, and lastly, call the function using the text and number entered.

str=input("Enter the string to be encrypted")n=int(input("Enter the key "))encrypt(str, n)

Say for example; The user enters the text – “hide me from others” and I want the text to be encrypted such that h is replaced by k and so on. The user would therefore enter 3 for the number. The text now becomes “klgh ph iurp rwkhuv”.

Similarly, we can create a decrypt function that can be used by the user at the other end to get the original text back. For that, the only change we would do is subtract the number from the index this time to get the index of the original character. We will have to create the final encrypted text as global so that we can later pass the text to the decrypt function.

CODE

letters=[‘a’,’b’,’c’,’d’,’e’,’f’,’g’,’h’,’i’,’j’,’k’,’l’,’m’,’n’,’o’,’p’,’q’,’r’,’s’,’t’,’u’,’v’,’w’,’x’,’y’,’z’]playing = ’ ’final = ‘ ‘org = ‘ ‘def encrypt(str,n):result = []for x in str:if x = = “ “:converted = ‘ ‘result.append(converted)else:converted = (letters.index(x) +n) %26result.append(letters[converted])final = ‘ ‘.join(result)print(final)return finaldef decrypt(str,n):back = []for x in str:if x = = “ “:original = ‘ ‘back.append(original)else:original = (letters.index(x) -n) %26back.append(letters[original])org = ‘ ‘.join(result)print(org)str=input(“enter the string to be encrypted”)n=int(input(“enter the key”))final=encrypt(str,n)print(“let’s decrypt the text”)decrypt(final,n)

CONCLUSION

The simple algorithm shown above can be modified to make the code difficult to crack. The ciphers used today, are a combination of mathematical rules and hash functions. So, to introduce Cryptography to kids, it’s good to start with simple algorithms. You are all set now to code and encrypt text with python. Happy Coding !!

Are you seeking introductory or advanced online python for kids coding classes? At SkoolofCode, we offer project-based learning modules where students use live code to find logical and inventive solutions to problems.So, why wait and Book a FREE trial class today.

By – Divya Dalal, an educator working with SkoolofCode taking Scratch and Python classes. She has done MCA and Masters in Technology in Software Engineering.

Cryptography Code To Encrypt String In Python (2024)
Top Articles
Exchange-Traded Funds (ETFs) | iShares UK – BlackRock
The Basics of Investing in Real Estate | The Motley Fool
The Tribes and Castes of the Central Provinces of India, Volume 3
Canary im Test: Ein All-in-One Überwachungssystem? - HouseControllers
Culver's Flavor Of The Day Wilson Nc
Polyhaven Hdri
Sportsman Warehouse Cda
Jonathan Freeman : "Double homicide in Rowan County leads to arrest" - Bgrnd Search
Bloxburg Image Ids
Notary Ups Hours
Overzicht reviews voor 2Cheap.nl
My.doculivery.com/Crowncork
How Many Slices Are In A Large Pizza? | Number Of Pizzas To Order For Your Next Party
Samsung Galaxy S24 Ultra Negru dual-sim, 256 GB, 12 GB RAM - Telefon mobil la pret avantajos - Abonament - In rate | Digi Romania S.A.
Nwi Arrests Lake County
Dutch Bros San Angelo Tx
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
Char-Em Isd
Arre St Wv Srj
Locate At&T Store Near Me
Army Oubs
Rural King Credit Card Minimum Credit Score
Jeff Now Phone Number
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Adt Residential Sales Representative Salary
Sussyclassroom
Synergy Grand Rapids Public Schools
Webworx Call Management
Watertown Ford Quick Lane
Bolly2Tolly Maari 2
Infinite Campus Asd20
Lindy Kendra Scott Obituary
Keshi with Mac Ayres and Starfall (Rescheduled from 11/1/2024) (POSTPONED) Tickets Thu, Nov 1, 2029 8:00 pm at Pechanga Arena - San Diego in San Diego, CA
Tracking every 2024 Trade Deadline deal
Shia Prayer Times Houston
Desales Field Hockey Schedule
Capital Hall 6 Base Layout
Nicole Wallace Mother Of Pearl Necklace
Ixl Lausd Northwest
Giantess Feet Deviantart
Autozone Locations Near Me
Caderno 2 Aulas Medicina - Matemática
Fifty Shades Of Gray 123Movies
Fetus Munchers 1 & 2
Craigs List Hartford
Ig Weekend Dow
Citizens Bank Park - Clio
Air Sculpt Houston
2121 Gateway Point
One Facing Life Maybe Crossword
Texas Lottery Daily 4 Winning Numbers
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 5641

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.