I had troubles compiling all the most commonly mentioned cryptography libraries on my Windows 7 system and for Python 3.5.

This is the solution that finally worked for me.

from cryptography.fernet import Fernet
key = Fernet.generate_key() #this is your "password"
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(b"Hello stackoverflow!")
decoded_text = cipher_suite.decrypt(encoded_text)
Answer from KRBA on Stack Overflow
Top answer
1 of 4
3

Here is a solution, for small letters only. It can easily be modified to handle also capital letters, by adding them to the text strings.

As can be seen, the space character is at the same position in both lists. This is not necessary, as any character can be translated to any other. However if the decrypted or encrypted is not containing unique characters only, the program will break down.

Copydecrypted = b"abcdefghijklmnopqrstuvwxyz "
encrypted = b"qwertyuiopasdfghjklzxcvbnm "

encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)

result = ''
choice = ''
message = ''

while choice != '0':
    choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")

    if choice == '1':
        message = input('\nEnter message for encryption: ')
        result = message.translate(encrypt_table)
        print(result + '\n\n')

    elif choice == '2':
        message = input('\nEnter message to decrypt: ')
        result = message.translate(decrypt_table)
        print(result + '\n\n')

    elif choice != '0':
        print('You have entered an invalid input, please try again. \n\n')
2 of 4
1

Ok, so a few things here...

First I'll give you exactly what you were looking for and explain what I used and some of the changes that needed to be made to your original code. Then I'll explain some inherent issues what what you're trying to do and suggest some areas to read up on/some ways you might want to improve what you've got.

Here's the code you're looking for (while retaining the same flow as what you submitted put above):

Copyimport random

result = ''
choice = ''
message = ''

characters_in_order = [chr(x) for x in range(32,127)]

while choice != 0:
    choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")

    if str(choice) == '1':
        message = input('\nEnter message for encryption: ')
        
        r_seed = input('Enter an integer to use as a seed: ')
        random.seed(r_seed)
        shuffled_list = [chr(x) for x in range(32,127)]
        random.shuffle(shuffled_list)

        for i in range(0, len(message)):
            result += shuffled_list[characters_in_order.index(message[i])]

        print(result + '\n\n')
        result = ''

    elif str(choice) == '2':
        message = input('\nEnter message to decrypt: ')

        r_seed = input('Enter an integer to use as a seed (should be the same one used to encrypt): ')
        random.seed(r_seed)
        shuffled_list = [chr(x) for x in range(32,127)]
        random.shuffle(shuffled_list)

        for i in range(0, len(message)):
            result += characters_in_order[shuffled_list.index(message[i])]

        print(result + '\n\n')
        result = ''

    elif str(choice) != '0':
        print('You have entered an invalid input, please try again. \n\n')

You'll notice that I set a global 'characters in order' list, which is just every ASCII character (32-126) in order. I also imported the 'random' module and used this to shuffle the characters in order according to a seed that the user inputs. As long as this seed is the same on the encryption and decryption end, it will produce the same shuffled list and it should work to encrypt or decipher the same string. Also notice the str() around your input choices. Without that, the user had to input '1', rather than 1 to submit a choice without an error.

All of that said...

  1. Notice that the way the new function works is by looking at a character's index in one list and pulling out the character at that index in another. The method you were using, of incrementing or decrementing a character's ASCII code is basic (though not much more basic than this), but it also has a pretty critical flaw, which is that characters on one end or another of the ASCII set wouldn't return ASCII characters. If you were encrypting it at a bit-level, which would be preferred, this wouldn't matter/would be irrelevant, but here you're not going to get the kind of string back that you want if you were to, for example, enter a [space] (ASCII 32) into your plaintext to be encrypted.
  2. If you're interested, you might want to read up on symmetric key encryption/DES for some ideas on how encryption is really done, though props on the start/interest and this can certainly be a fun way to create some sort of cryptogram puzzle or something along those lines. I won't pretend to be any kind of expert, but I can at least point you in the write direction. (https://en.wikipedia.org/wiki/Data_Encryption_Standard https://en.wikipedia.org/wiki/Symmetric-key_algorithm)
  3. Consider having your code read in a .txt file and print out to a .txt file, rather than using user input for the message.

Again, I'm not an expert by any means and there are definitely some fun uses of the kind of program you're aiming for, just trying to point you in the right direction if this is something that you're interested in. Hope all of that is helpful!

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-encrypt-and-decrypt-strings-in-python
How to Encrypt and Decrypt Strings in Python? - GeeksforGeeks
August 14, 2024 - The receiver needs the key for decryption, so a safe way need for transferring keys. Anyone with the key can read the data in the middle. ... Install the python cryptography library with the following command.
🌐
GeeksforGeeks
geeksforgeeks.org › python › encrypt-and-decrypt-files-using-python
Encrypt and Decrypt Files using Python - GeeksforGeeks
June 20, 2025 - from cryptography.fernet import Fernet # Load the key from the .key file with open('filekey.key', 'rb') as f: key = f.read() # Create a Fernet object using the key fernet = Fernet(key) # Open the file to be encrypted in binary read mode with open('nba.csv', 'rb') as f: original = f.read() # Encrypt the file content encrypted = fernet.encrypt(original) # Overwrite the original file with the encrypted data with open('nba.csv', 'wb') as f: f.write(encrypted) The nba.csv file before executing the above program: The nba.csv file after executing the above program: ... Fernet(key) creates an encryption tool that can encrypt and decrypt using this key.
🌐
Medium
medium.com › @info_82002 › a-beginners-guide-to-encryption-and-decryption-in-python-12d81f6a9eac
A Beginner’s Guide to Encryption and Decryption in Python
August 6, 2024 - Learn to implement encryption and decryption in Python with easy-to-follow examples using libraries like cryptography and PyCryptodome. Secure your data!
🌐
Reddit
reddit.com › r/python › basic encryption/decryption program
r/Python on Reddit: Basic Encryption/Decryption program
November 5, 2021 -

Hello everyone, I hope you're having a good day.

Today when going through some old programs in my files, I stumbled upon an encryption and decryption program that I made. It was quite simple, you enter some text into the program and it changes each character in the sentence to a different one. Here's the link to the code:

Encryption-decryption

The original code for this was very long since I was still getting the hang of loops and thought it was difficult to implement, but I've added the original code to the repository nonetheless for the sake of comparing the improvement in the code (if you get triggered by the code, don't worry, I don't code like that anymore).

My next move for the code is to try and make it encrypt entire files, and hopefully generate a random key to encrypt the file as well for better security and save the time on making large lists to encrypt it for me. If you happen to have an idea on how to do this, or any idea or critic at all, I'd love to know!

Hopefully I can make this program more powerful at its purpose, but for now it's there to simply show how encryption and decryption works.

Have an amazing day!

🌐
Medium
medium.com › @sunilnepali844 › complete-guide-to-encryption-and-decryption-in-python-for-beginners-61c2343c3f2b
Complete Guide to Encryption and Decryption in Python (For Beginners) | by Sunil Nepali | Medium
June 19, 2025 - This blog covers everything you need to know about encryption and decryption in Python. It’s beginner-friendly and includes clear code examples.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › cryptography_with_python › cryptography_with_python_quick_guide.htm
Cryptography with Python - Quick Guide
Every letter is shifted by 13 places to encrypt or decrypt the message. The following diagram explains the ROT13 algorithm process pictorially − · The program implementation of ROT13 algorithm is as follows − · rot13trans = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm') # Function to translate plain text def rot13(text): return text.translate(rot13trans) def main(): txt = "ROT13 Algorithm" print(rot13(txt)) if __name__ == "__main__": main()
🌐
Oreate AI
oreateai.com › blog › implementing-a-simple-encryption-and-decryption-program-with-python › cf416c2f6ec98b75ac3151cce2d01806
Implementing a Simple Encryption and Decryption Program With Python - Oreate AI Blog
December 22, 2025 - First, we must understand that text is encoded; English uses ASCII encoding while Chinese uses GB18030. What is a character set? Then what? We approach this from top to bottom, refining step by step. ... a = input() b = "" for i in a: # Note spaces b = b + chr(ord(i) + 1) print(b) # System built-in function
🌐
AskPython
askpython.com › home › how to write an encryption program in python?
How to Write an Encryption Program in Python? - AskPython
March 16, 2023 - Here is the flow chart of the data transmission between sender and receiver, where the sender sends Hello! as a message which is then converted to a cipher text using an encryption key. The receiver decrypts the cipher text and obtains the original message using a decryption key. ... There are a few ways to write an encryption program in python.
🌐
Python Programming
pythonprogramming.net › encryption-and-decryption-in-python-code-example-with-explanation
Python Programming Tutorials
# basically, its a function, and you define it, followed by the param # followed by a colon, # ex = lambda x: x+5 pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING # encrypt with AES, encode with base64 EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) # generate a randomized secret key with urandom secret = os.urandom(BLOCK_SIZE) print 'encryption key:',secret # creates the cipher obj using the key cipher = AES.new(secret) # encodes you private info!
🌐
The Python Code
thepythoncode.com › article › encrypt-decrypt-files-symmetric-python
How to Encrypt and Decrypt Files in Python - The Python Code
In this tutorial, you will learn how to use Python to encrypt files or any byte object (also string objects) using the cryptography library. We will use symmetric encryption, which means the same key we used to encrypt data is also usable for decryption. There are a lot of encryption algorithms out there.
🌐
LogRocket
blog.logrocket.com › home › implementing cryptography with python
Implementing cryptography with Python - LogRocket Blog
June 4, 2024 - With the input() method, we take user input for the program. Then, a variable is created in ciphertext, which we call encrypt_caesar( num, text). The print statement is used to print the encoded ciphertext.
🌐
Learn Coding Fast
learncodingfast.com › home › python tutorial: how to write a simple encryption/decryption program
Python Tutorial: How to write a simple encryption/decryption program | Learn Coding Fast
August 29, 2020 - Suppose we start off with the string ‘Python’. Here’s what happens as the program loops through the word ‘Python’ to get the resulting encrypted message ‘Nwrfml’: Finally, after encrypting the message, the next two lines (14 and 15) print the string result and reset the result variable back to an empty string. That’s it. That’s how we can write a simple encryption program. The next few lines (17 to 24) does the reverse and decrypts our message by adding 2 to the numerical representation of our message. elif choice == '2': message = input("\nEnter the message to decrypt: ") for i in range(0, len(message)): result = result + chr(ord(message[i]) + 2) print (result + '\n\n') result = '' elif choice != '-1': print ("You have entered an invalid choice.
🌐
Medium
medium.com › @projectsexplained › simple-text-encryption-and-decryption-in-python-a4787f9a7aae
Simple Text Encryption and Decryption in Python | by Projects Explained | Medium
August 21, 2023 - I’m Jason, and today we’re ... and decryption. Don’t let the tech jargon scare you — I’ll guide you through every step. By the end of this, you’ll be able to send secret messages just like a spy! Basic Python Knowledge: It’s helpful to have a basic understanding of Python programming concepts like variables, loops, functions, and if statements · Python Installed: Make sure you have ...
🌐
Null Byte
null-byte.wonderhowto.com › how-to › encrypt-and-decrypt-text-python-0132905
How To Encrypt And Decrypt Text In Python :: Null Byte
January 20, 2012 - Y/N\n") if options=='y': loop=5 if options=='n': loop=0 if option=='b': encoded=raw_input("Please Enter The Encoded String:\n") letter=3 while letter==3: secret=raw_input("Please Enter The Decryption Key:\n") countTotal= (len(secret)) #this checks the encryption key to ensure it matches the correct length if countTotal==16: cipher = AES.new(secret) letter=0 decoded = DecodeAES(cipher, encoded) print 'Decrypted string:', decoded options=raw_input("Would You Like To Encrypt/Decrypt Again? Y/N\n") if options=='y': loop=5 if options=='n': loop=0 else: print "Please Ensure The Key You Entered Is 16 Characters In Length\n" letter=3 if loop==0: print "Goodbye!!" time.sleep(2) exit #exits the program if desired by user
🌐
DevGenius
blog.devgenius.io › creating-custom-encrypting-encoding-and-decrypting-program-in-python-5a607bd8b67
Creating CUSTOM Encrypting(Encoding) and Decrypting program in Python | by Nagaraj Vaidya | Dev Genius
September 2, 2022 - Let’s understand the functions that we are gonna create in this program. We require one function to read the keys, one function to encrypt the text and another to decrypt the text, that’s it! Let’s create encrypted values for each characters.
Top answer
1 of 1
2

You had quite a number of confusions. Look at encrypt, for example. You pass in text, then you immediately set text='', thereby destroying the message that was input. Similarly, in decrypt, you pass in cipherText, but you run message.translate. And your functions need to return their results, not print them. Let the caller decide what to do with the returned results.

Also, it is a good practice to collect your functions at the top of the module, so you don't fool yourself into believing that things get called in the wrong order.

Here is your code, modified so that it works:

def encrypt(text):
    result = text.translate(encrypt_table)
    return result

def decrypt(message):
    result = message.translate(decrypt_table)
    return result

decrypted = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
encrypted = b"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM "

encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)

while True:
    text = input("Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")

    if text == '1':
        text = input('Enter message for encryption: ')
        result =  encrypt(text)
        print(result)
    elif text == '2':
        cipherText = input('Enter message to decrypt: ')
        result = decrypt(cipherText)
        print(result)
    elif text == '0':
        break
    else:
        print('You have entered an invalid input, please try again. \n\n')

Note that encrypt and decrypt don't really need to store in a temporary variable. The only reason to do that is because it is more convenient for debugging, to add a quick print(result) before the return.

🌐
Nitratine
nitratine.net › blog › post › encryption-and-decryption-in-python
Encryption and Decryption in Python - Nitratine
In this post, I discuss how to encrypt and decrypt messages in Python using symmetric encryption. I will demonstrate how to create keys, save keys and how to encrypt messages and text.
🌐
Towards Data Science
towardsdatascience.com › home › latest › encrypt and decrypt files using python – python programming
Encrypt and Decrypt Files using Python - Python Programming | Towards Data Science
March 5, 2025 - This article introduces basic symmetric file encryption and decryption using Python. We have discussed some parts of cryptography library as well as created a full process example. Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Programming ...