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
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-encrypt-and-decrypt-strings-in-python
How to Encrypt and Decrypt Strings in Python? - GeeksforGeeks
August 14, 2024 - Instance the Fernet class with the encryption key. Then encrypt the string with the Fernet instance. Then it can be decrypted with Fernet class instance and it should be instanced with the same key used for encryption.
Discussions

encryption - simple encrypt/decrypt lib in python with private key - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... key = '1234' string = 'hello world' encrypted_string = encrypt(key, string) decrypt(key, encrypted_string) More on stackoverflow.com
🌐 stackoverflow.com
Encypting and Decrypting
So I am working on a project for school in which I need to make a code to encrypt and decrypt text seperatly from eachother. My current code works to encrypt and decrypt at the same time but I can’t seem to get it working seperatly. My code: from cryptography.fernet import Fernet # we will ... More on discuss.python.org
🌐 discuss.python.org
13
0
January 4, 2022
Python Newbie - Encryption and decryption help
Conceptually, encryption and decryption have to be inverse functions (with the exception of ROT13, because the function is its own inverse.) Here's your "encryption" algorithm: encrypted += char.translate(mapping) here's your "decryption" algorithm: decrypted += char.translate(mapping) Maybe you can see, as I do, that these are the same algorithm. More on reddit.com
🌐 r/learnpython
6
0
May 16, 2023
What is the simplest way to encrypt images and text files in python?
I'm going to assume you are trying to learn how to do this and don't just want a solution posted. The simplest way is to use the cryptography library , which you'll need to install (usually pip install cryptography). If you aren't sure how to install modules, let me know, but I'll proceed assuming you either know or can find it. Next, we want to use the Fernet module to encrypt and decrypt files. Note that this encrypts and decrypts files, not just images and text, as there's no real meaningful distinction there. For illustration purposes, I'm going to use basic input and no looping, but in an actual program you'd want to save and load to files and add looping functionality for multiple files. I'm also having it create copies of the encrypted files as it's safer and less complicated. Once we're set up, we import the module and create a function to generate a key: from cryptography.fernet import Fernet user_key = input("Generate new key (y/n) ") if user_key.lower() == 'y': user_key = Fernet.generate_key() with open('key.key', 'wb') as f: f.write(user_key) else: with open('key.key', 'rb') as f: user_key = f.read() Now we've got a key, which is a string the program will use to encrypt or decrypt files. IMPORTANT: If you lose your key, you cannot decrypt the file. Be sure to save your keys somewhere safe. I save it to a file here because trying to copy and paste keys can be problematic. Why Fernet? There are multiple options, but I believe this is the easiest, using a direct "secret key" form of encryption. Encryption is a huge topic and there are all sorts of different methods for encrypting files, but things like public keys vs. private keys and different encryption algorithms are far beyond the beginner level and aren't necessary to know to get started. Just keep in mind this was chosen for simplicity while still being quite secure, however, there are many other options that may be better depending on the purpose of your encryption. Next, we need to encrypt a file. This is just a matter of reading the file and encrypting the contents, then saving the file again: file = input("Enter a file to encrypt (enter to skip): ") if file != '': with open(file, 'rb') as f: data = f.read() fernet = Fernet(user_key) encrypted = fernet.encrypt(data) new_file = file[:-4] + '_encrypted' + file[-4:] with open(new_file, 'wb') as f: f.write(encrypted) What's going on here? First, we read the file we want to encrypt as bytes (this is important). Then we create a Fernet object that can be used for encryption with our user key. This uses encrypt to encrypt the contents of the file. The new_file line just adds _encrypted into the file name so it doesn't overwrite the contents; if you like to live dangerously, just use file again in the second with block, which will overwrite the existing file. That's basically it to get an encrypted file. There are a lot of things you could do to make this more user-friendly, but for "simplest" this is about as simple as you can get. Having an encrypted file is kind of pointless if we can't decrypt it. So our next block will do just that: file = input("Enter a file to decrypt (enter to skip): ") if file != '': with open(file, 'rb') as f: data = f.read() fernet = Fernet(user_key) decrypted = fernet.decrypt(data) new_file = file[:-4] + '_decrypted' + file[-4:] with open(new_file, 'wb') as f: f.write(decrypted) Unsurprisingly, it's the same process, you just use decrypt instead of encrypt. Be sure to enter your encrypted file, not the original! You'll get an error if you try to decrypt a file that isn't encrypted. And that's basically it. This could be greatly improved by adding better error handling, saving keys more securely, etc. If you just want something encrypted that you can later decrypt, though, and someone isn't going to have access to the file on the computer to encrypted it on (and therefore can read your key file), this should be enough to get you started. Let me know if you have questions! More on reddit.com
🌐 r/learnpython
7
8
September 9, 2024
Top answer
1 of 13
242

Python has no built-in encryption schemes, no. You also should take encrypted data storage serious; trivial encryption schemes that one developer understands to be insecure and a toy scheme may well be mistaken for a secure scheme by a less experienced developer. If you encrypt, encrypt properly.

You don’t need to do much work to implement a proper encryption scheme however. First of all, don’t re-invent the cryptography wheel, use a trusted cryptography library to handle this for you. For Python 3, that trusted library is cryptography.

I also recommend that encryption and decryption applies to bytes; encode text messages to bytes first; stringvalue.encode() encodes to UTF8, easily reverted again using bytesvalue.decode().

Last but not least, when encrypting and decrypting, we talk about keys, not passwords. A key should not be human memorable, it is something you store in a secret location but machine readable, whereas a password often can be human-readable and memorised. You can derive a key from a password, with a little care.

But for a web application or process running in a cluster without human attention to keep running it, you want to use a key. Passwords are for when only an end-user needs access to the specific information. Even then, you usually secure the application with a password, then exchange encrypted information using a key, perhaps one attached to the user account.

Symmetric key encryption

Fernet – AES CBC + HMAC, strongly recommended

The cryptography library includes the Fernet recipe, a best-practices recipe for using cryptography. Fernet is an open standard, with ready implementations in a wide range of programming languages and it packages AES CBC encryption for you with version information, a timestamp and an HMAC signature to prevent message tampering.

Fernet makes it very easy to encrypt and decrypt messages and keep you secure. It is the ideal method for encrypting data with a secret.

I recommend you use Fernet.generate_key() to generate a secure key. You can use a password too (next section), but a full 32-byte secret key (16 bytes to encrypt with, plus another 16 for the signature) is going to be more secure than most passwords you could think of.

The key that Fernet generates is a bytes object with URL- and file-safe base64 characters, so printable:

from cryptography.fernet import Fernet

key = Fernet.generate_key()  # store in a secure location
# PRINTING FOR DEMO PURPOSES ONLY, don't do this in production code
print("Key:", key.decode())

To encrypt or decrypt messages, create a Fernet() instance with the given key, and call the Fernet.encrypt() or Fernet.decrypt(), both the plaintext message to encrypt and the encrypted token are bytes objects.

encrypt() and decrypt() functions would look like:

from cryptography.fernet import Fernet

def encrypt(message: bytes, key: bytes) -> bytes:
    return Fernet(key).encrypt(message)

def decrypt(token: bytes, key: bytes) -> bytes:
    return Fernet(key).decrypt(token)

Demo:

>>> key = Fernet.generate_key()
>>> print(key.decode())
GZWKEhHGNopxRdOHS4H4IyKhLQ8lwnyU7vRLrM3sebY=
>>> message = 'John Doe'
>>> token = encrypt(message.encode(), key)
>>> print(token)
'gAAAAABciT3pFbbSihD_HZBZ8kqfAj94UhknamBuirZWKivWOukgKQ03qE2mcuvpuwCSuZ-X_Xkud0uWQLZ5e-aOwLC0Ccnepg=='
>>> decrypt(token, key).decode()
'John Doe'

Fernet with password – key derived from password, weakens the security somewhat

You can use a password instead of a secret key, provided you use a strong key derivation method. You do then have to include the salt and the HMAC iteration count in the message, so the encrypted value is not Fernet-compatible anymore without first separating salt, count and Fernet token:

import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

backend = default_backend()
iterations = 100_000

def _derive_key(password: bytes, salt: bytes, iterations: int = iterations) -> bytes:
    """Derive a secret key from a given password and salt"""
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(), length=32, salt=salt,
        iterations=iterations, backend=backend)
    return b64e(kdf.derive(password))

def password_encrypt(message: bytes, password: str, iterations: int = iterations) -> bytes:
    salt = secrets.token_bytes(16)
    key = _derive_key(password.encode(), salt, iterations)
    return b64e(
        b'%b%b%b' % (
            salt,
            iterations.to_bytes(4, 'big'),
            b64d(Fernet(key).encrypt(message)),
        )
    )

def password_decrypt(token: bytes, password: str) -> bytes:
    decoded = b64d(token)
    salt, iter, token = decoded[:16], decoded[16:20], b64e(decoded[20:])
    iterations = int.from_bytes(iter, 'big')
    key = _derive_key(password.encode(), salt, iterations)
    return Fernet(key).decrypt(token)

Demo:

>>> message = 'John Doe'
>>> password = 'mypass'
>>> password_encrypt(message.encode(), password)
b'9Ljs-w8IRM3XT1NDBbSBuQABhqCAAAAAAFyJdhiCPXms2vQHO7o81xZJn5r8_PAtro8Qpw48kdKrq4vt-551BCUbcErb_GyYRz8SVsu8hxTXvvKOn9QdewRGDfwx'
>>> token = _
>>> password_decrypt(token, password).decode()
'John Doe'

Including the salt in the output makes it possible to use a random salt value, which in turn ensures the encrypted output is guaranteed to be fully random regardless of password reuse or message repetition. Including the iteration count ensures that you can adjust for CPU performance increases over time without losing the ability to decrypt older messages.

A password alone can be as safe as a Fernet 32-byte random key, provided you generate a properly random password from a similar size pool. 32 bytes gives you 256 ^ 32 number of keys, so if you use an alphabet of 74 characters (26 upper, 26 lower, 10 digits and 12 possible symbols), then your password should be at least math.ceil(math.log(256 ** 32, 74)) == 42 characters long. However, a well-selected larger number of HMAC iterations can mitigate the lack of entropy somewhat as this makes it much more expensive for an attacker to brute force their way in.

Just know that choosing a shorter but still reasonably secure password won’t cripple this scheme, it just reduces the number of possible values a brute-force attacker would have to search through; make sure to pick a strong enough password for your security requirements.

Alternatives

Obscuring

An alternative is not to encrypt. Don't be tempted to just use a low-security cipher, or a home-spun implementation of, say Vignere. There is no security in these approaches, but may give an inexperienced developer that is given the task to maintain your code in future the illusion of security, which is worse than no security at all.

If all you need is obscurity, just base64 the data; for URL-safe requirements, the base64.urlsafe_b64encode() function is fine. Don't use a password here, just encode and you are done. At most, add some compression (like zlib):

import zlib
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

def obscure(data: bytes) -> bytes:
    return b64e(zlib.compress(data, 9))

def unobscure(obscured: bytes) -> bytes:
    return zlib.decompress(b64d(obscured))

This turns b'Hello world!' into b'eNrzSM3JyVcozy_KSVEEAB0JBF4='.

Integrity only

If all you need is a way to make sure that the data can be trusted to be unaltered after having been sent to an untrusted client and received back, then you want to sign the data, you can use the hmac library for this with SHA1 (still considered secure for HMAC signing) or better:

import hmac
import hashlib

def sign(data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
    assert len(key) >= algorithm().digest_size, (
        "Key must be at least as long as the digest size of the "
        "hashing algorithm"
    )
    return hmac.new(key, data, algorithm).digest()

def verify(signature: bytes, data: bytes, key: bytes, algorithm=hashlib.sha256) -> bytes:
    expected = sign(data, key, algorithm)
    return hmac.compare_digest(expected, signature)

Use this to sign data, then attach the signature with the data and send that to the client. When you receive the data back, split data and signature and verify. I've set the default algorithm to SHA256, so you'll need a 32-byte key:

key = secrets.token_bytes(32)

You may want to look at the itsdangerous library, which packages this all up with serialisation and de-serialisation in various formats.

Using AES-GCM encryption to provide encryption and integrity

Fernet builds on AEC-CBC with a HMAC signature to ensure integrity of the encrypted data; a malicious attacker can't feed your system nonsense data to keep your service busy running in circles with bad input, because the ciphertext is signed.

The Galois / Counter mode block cipher produces ciphertext and a tag to serve the same purpose, so can be used to serve the same purposes. The downside is that unlike Fernet there is no easy-to-use one-size-fits-all recipe to reuse on other platforms. AES-GCM also doesn't use padding, so this encryption ciphertext matches the length of the input message (whereas Fernet / AES-CBC encrypts messages to blocks of fixed length, obscuring the message length somewhat).

AES256-GCM takes the usual 32 byte secret as a key:

key = secrets.token_bytes(32)

then use

import binascii, time
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.exceptions import InvalidTag

backend = default_backend()

def aes_gcm_encrypt(message: bytes, key: bytes) -> bytes:
    current_time = int(time.time()).to_bytes(8, 'big')
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.GCM(iv), backend=backend)
    encryptor = cipher.encryptor()
    encryptor.authenticate_additional_data(current_time)
    ciphertext = encryptor.update(message) + encryptor.finalize()        
    return b64e(current_time + iv + ciphertext + encryptor.tag)

def aes_gcm_decrypt(token: bytes, key: bytes, ttl=None) -> bytes:
    algorithm = algorithms.AES(key)
    try:
        data = b64d(token)
    except (TypeError, binascii.Error):
        raise InvalidToken
    timestamp, iv, tag = data[:8], data[8:algorithm.block_size // 8 + 8], data[-16:]
    if ttl is not None:
        current_time = int(time.time())
        time_encrypted, = int.from_bytes(data[:8], 'big')
        if time_encrypted + ttl < current_time or current_time + 60 < time_encrypted:
            # too old or created well before our current time + 1 h to account for clock skew
            raise InvalidToken
    cipher = Cipher(algorithm, modes.GCM(iv, tag), backend=backend)
    decryptor = cipher.decryptor()
    decryptor.authenticate_additional_data(timestamp)
    ciphertext = data[8 + len(iv):-16]
    return decryptor.update(ciphertext) + decryptor.finalize()

I've included a timestamp to support the same time-to-live use-cases that Fernet supports.

Other approaches on this page, in Python 3

AES CFB - like CBC but without the need to pad

This is the approach that All Іѕ Vаиітy follows, albeit incorrectly. This is the cryptography version, but note that I include the IV in the ciphertext, it should not be stored as a global (reusing an IV weakens the security of the key, and storing it as a module global means it'll be re-generated the next Python invocation, rendering all ciphertext undecryptable):

import secrets
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_cfb_encrypt(message, key):
    algorithm = algorithms.AES(key)
    iv = secrets.token_bytes(algorithm.block_size // 8)
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(message) + encryptor.finalize()
    return b64e(iv + ciphertext)

def aes_cfb_decrypt(ciphertext, key):
    iv_ciphertext = b64d(ciphertext)
    algorithm = algorithms.AES(key)
    size = algorithm.block_size // 8
    iv, encrypted = iv_ciphertext[:size], iv_ciphertext[size:]
    cipher = Cipher(algorithm, modes.CFB(iv), backend=backend)
    decryptor = cipher.decryptor()
    return decryptor.update(encrypted) + decryptor.finalize()

This lacks the added armoring of an HMAC signature and there is no timestamp; you’d have to add those yourself.

The above also illustrates how easy it is to combine basic cryptography building blocks incorrectly; All Іѕ Vаиітy‘s incorrect handling of the IV value can lead to a data breach or all encrypted messages being unreadable because the IV is lost. Using Fernet instead protects you from such mistakes.

AES ECB – not secure

If you previously implemented AES ECB encryption and need to still support this in Python 3, you can do so still with cryptography too. The same caveats apply, ECB is not secure enough for real-life applications. Re-implementing that answer for Python 3, adding automatic handling of padding:

from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend

backend = default_backend()

def aes_ecb_encrypt(message, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(cipher.algorithm.block_size).padder()
    padded = padder.update(msg_text.encode()) + padder.finalize()
    return b64e(encryptor.update(padded) + encryptor.finalize())

def aes_ecb_decrypt(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
    padded = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
    return unpadder.update(padded) + unpadder.finalize()

Again, this lacks the HMAC signature, and you shouldn’t use ECB anyway. The above is there merely to illustrate that cryptography can handle the common cryptographic building blocks, even the ones you shouldn’t actually use.

2 of 13
86

Assuming you are only looking for simple obfuscation that will obscure things from the very casual observer, and you aren't looking to use third party libraries. I'd recommend something like the Vigenere cipher. It is one of the strongest of the simple ancient ciphers.

Vigenère cipher

It's quick and easy to implement. Something like:

import base64

def encode(key, string):
    encoded_chars = []
    for i in xrange(len(string)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = "".join(encoded_chars)
    return base64.urlsafe_b64encode(encoded_string)

Decode is pretty much the same, except you subtract the key.

It is much harder to break if the strings you are encoding are short, and/or if it is hard to guess the length of the passphrase used.

If you are looking for something cryptographic, PyCrypto is probably your best bet, though previous answers overlook some details: ECB mode in PyCrypto requires your message to be a multiple of 16 characters in length. So, you must pad. Also, if you want to use them as URL parameters, use base64.urlsafe_b64_encode(), rather than the standard one. This replaces a few of the characters in the base64 alphabet with URL-safe characters (as it's name suggests).

However, you should be ABSOLUTELY certain that this very thin layer of obfuscation suffices for your needs before using this. The Wikipedia article I linked to provides detailed instructions for breaking the cipher, so anyone with a moderate amount of determination could easily break it.

🌐
Codez Up
codezup.com › home › encrypt and decrypt string using key in python
Encrypt and Decrypt String using Key in Python | Codez Up
March 13, 2021 - This function lets you encrypt the string message based on the key you suggest. LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ' LETTERS = LETTERS.lower() def encrypt(message, key): encrypted = '' for chars in message: if chars ...
🌐
Finxter
blog.finxter.com › home › learn python blog › two easy ways to encrypt and decrypt python strings
Two Easy Ways to Encrypt and Decrypt Python Strings - Be on the Right Side of Change
February 1, 2023 - To encrypt and decrypt a Python string, install and import the cryptography library, generate a Fernet key, and create a Fernet object with it.
🌐
Delft Stack
delftstack.com › home › howto › python › python encrypt string
How to Encrypt a Python String | Delft Stack
February 2, 2024 - Then, we generate an encryption key that will be used for both encoding and decoding purposes. The Fernet class is instanced with the encryption key. The string is then encrypted with the Fernet instance. Finally, it is decrypted with the Fernet class instance. Symmetric-key Encryption is an effortless way for encrypting a string. The only drawback is it’s comparatively less secure. Anyone with the key can read the encrypted text. The RSA algorithm in Python implements the Asymmetric-key Encryption.
🌐
DevQA
devqa.io › encrypt-decrypt-data-python
How to Encrypt and Decrypt Data in Python using Cryptography Library
from cryptography.fernet import Fernet def generate_key(): """ Generates a key and save it into a file """ key = Fernet.generate_key() with open("secret.key", "wb") as key_file: key_file.write(key) def load_key(): """ Load the previously generated key """ return open("secret.key", "rb").read() def encrypt_message(message): """ Encrypts a message """ key = load_key() encoded_message = message.encode() f = Fernet(key) encrypted_message = f.encrypt(encoded_message) print(encrypted_message) if __name__ == "__main__": encrypt_message("encrypt this message") ... b'gAAAAABesCUIAcM8M-_Ik_-I1-JD0AzLZU8A8-AJITYCp9Mc33JaHMnYmRedtwC8LLcYk9zpTqYSaDaqFUgfz-tcHZ2TQjAgKKnIWJ2ae9GDoea6tw8XeJ4=' To decrypt the message, we just call the decrypt() method from the Fernet library.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-encrypt-and-decrypt-data-in-python
How to encrypt and decrypt data in Python
Here's a complete encryption and decryption workflow ? from cryptography.fernet import Fernet # Step 1: Generate key key = Fernet.generate_key() print("Key:", key.decode()) # Step 2: Create cipher instance cipher = Fernet(key) # Step 3: Encrypt ...
🌐
YouTube
youtube.com › watch
How to Encrypt and Decrypt in Python - Encrypting Strings in Python - YouTube
If you liked the content, please consider checking out my Patreon! - https://www.patreon.com/CodingUnderPressure/membership Hey everyone, today I go over how...
Published: December 2, 2019
🌐
Linux Hint
linuxhint.com › encrypt-string-python
Linux Hint – Linux Hint
April 11, 2023 - Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
CodeSpeedy
codespeedy.com › home › encryption and decryption of string using python
Encryption and Decryption of String using Python - CodeSpeedy
October 5, 2019 - output: Enter the string to Encrypt and decrypt : shravan Enter the key(Eg: 21) : 15 Encrypted String : hwgpkpc Decrypted String : shravan · Here is the code for Encryption and Decryption using Python programming language. In the above code, there are two functions Encryption() and Decryption() we will call them by passing parameters.
🌐
GitHub
gist.github.com › VJPranay › b4b3ae945d4a0c58d76f0cb6a0ff55f8
String encryption and decryption using Python · GitHub
String encryption and decryption using Python . GitHub Gist: instantly share code, notes, and snippets.
🌐
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 - Python, with its extensive libraries, makes it relatively straightforward to implement these techniques. In this blog, we’ll explore how to implement encryption and decryption in Python using different libraries and methods. Fernet is a part of the cryptography library and provides symmetric encryption. Symmetric encryption means the same key is used for both encryption and decryption.
Top answer
1 of 5
28

pyDES is a DES and Triple-DES implementation completely written in python.

Here's a simple and portable example that should be secure enough for basic string encryption needs. Just put the pyDES module in the same folder as your program and try it out:

Sender's computer

>>> from pyDES import *  # pyDes if installed from pip
>>> ciphertext = triple_des('a 16 or 24 byte password').encrypt("secret message", padmode=2)  #plain-text usually needs padding, but padmode = 2 handles that automatically
>>> ciphertext
')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2'  #gibberish

Recipient's computer

>>> from pyDES import *
>>> plain_text = triple_des('a 16 or 24 byte password').decrypt(')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2', padmode=2)
>>> plain_text
"secret message"

You might get an error in Python3 from code of Recipient's computer

ValueError: pyDes can only work with encoded strings, not Unicode.

from pyDes import *

a = b')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2'
plain_text = triple_des('a 16 or 24 byte password').decrypt(a, padmode=2)
print(plain_text)

Just Add b at the beginning of the encrypted text. For clearer code, assign it to a new variable (in this case, it's a, and decrypt a in a normal way).

2 of 5
24

http://www.dlitz.net/software/pycrypto/ should do what you want.

Taken from their docs page.

>>> from Crypto.Cipher import DES
>>> obj=DES.new('abcdefgh', DES.MODE_ECB)
>>> plain="Guido van Rossum is a space alien."
>>> len(plain)
34
>>> obj.encrypt(plain)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: Strings for DES must be a multiple of 8 in length
>>> ciph=obj.encrypt(plain+'XXXXXX')
>>> ciph
'\021,\343Nq\214DY\337T\342pA\372\255\311s\210\363,\300j\330\250\312\347\342I\3215w\03561\303dgb/\006'
>>> obj.decrypt(ciph)
'Guido van Rossum is a space alien.XXXXXX'
🌐
Nitratine
nitratine.net › blog › post › encryption-and-decryption-in-python
Encryption and Decryption in Python - Nitratine
from cryptography.fernet import Fernet, InvalidToken key = b'' # Use one of the methods to get a key (it must be the same as used in encrypting) input_file = 'test.encrypted' output_file = 'test.txt' with open(input_file, 'rb') as f: data = f.read() # Read the bytes of the encrypted file fernet = Fernet(key) try: decrypted = fernet.decrypt(data) with open(output_file, 'wb') as f: f.write(decrypted) # Write the decrypted bytes to the output file # Note: You can delete input_file here if you want except InvalidToken as e: print("Invalid Key - Unsuccessfully decrypted") As stated in Fernet docs,
🌐
Python.org
discuss.python.org › python help
Encypting and Decrypting - Python Help - Discussions on Python.org
January 4, 2022 - So I am working on a project for school in which I need to make a code to encrypt and decrypt text seperatly from eachother. My current code works to encrypt and decrypt at the same time but I can’t seem to get it working seperatly. My code: from cryptography.fernet import Fernet # we will be encryting the below string. message =input("Give your message: ") # generate a key for encryptio and decryption # You can use fernet to generate # the key or use random key generator # here I'm using...
🌐
Reddit
reddit.com › r/learnpython › python newbie - encryption and decryption help
r/learnpython on Reddit: Python Newbie - Encryption and decryption help
May 16, 2023 -

Hey guys so I was doing the encryption and decryption function using str.maketrans().I am sure that there are numerous other ways to solve this problem, I have chosen this one. This is a menu based function wherein I will ask the user continuously to enter an option - Encrypt,Decrypt or exit. The functions work as expected except for 1 case that is :

Enter string: abc

Enter option : E

Encrypted code: xnz

Enter option: D

Decrypted code: xgv. Here I want it to turn back into plain text ie abc.

def encrypt(key,message):
# Define the mapping between letters and their corresponding replacements
mapping = str.maketrans('abcdefghijklmnopqrstuvwxyz', key)

# Use the mapping to encrypt each character in the message
encrypted = ''
text_string = message.lower()
for char in text_string:
    if char.isalpha():
        # If it's a letter, replace it with its corresponding replacement
        encrypted += char.translate(mapping)
    else:
        # Otherwise, keep the character as is (e.g. if it's a number or a space)
        encrypted += char

return encrypted

def decrypt(key,encrypted): # Define the mapping between replacements and their corresponding letters mapping = str.maketrans(key, 'abcdefghijklmnopqrstuvwxyz')

# Use the mapping to decrypt each character in the ciphertext
decrypted = ''
text_string = encrypted.lower()
for char in text_string:
    if char.isalpha():
        # If it's a replacement, replace it with its corresponding letter
        decrypted += char.translate(mapping)
    else:
        # Otherwise, keep the character as is (e.g. if it's a number or a space)
        decrypted += char

return decrypted

def main(): while True: key = 'xznlwebgjhqdyvtkfuompciasr' message=input("Enter the string : ") if message=="": print("Cannot be empty string ") else: while True: option = input(f'Select an option\nE: Encrypting function\nD: Decrypting function\nEX: exit\n') encrypted = encrypt(key, message) if option == 'E': encrypted =encrypt(key,message) print('The encrypted message is: ', encrypted) elif option == 'D': decrypted = decrypt(key, message) print('The decrypted message is :', decrypted) elif option == 'EX': break else: print("Invalid option")

main()

I am not sure how to pass the encypted text back to decrypt function. Thanks in advance!

🌐
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 - We’re shifting the letters in the alphabet by the ‘key’ number. Lowercase and uppercase letters are handled like champs. The encrypted message starts forming, character by character. And voila — your secret message is encrypted and ready to send! def decrypt(encrypted_message, key): decrypted = ""
🌐
DEV Community
dev.to › guardianangel › how-to-encrypt-a-text-using-python-key-and-text-and-decrypt-that-cipher-in-javascript-using-the-same-key-5dbm
How to encrypt a text using Python (key and text) and decrypt that cipher in JavaScript using the same key. - DEV Community
April 11, 2023 - This function uses the built-in crypto module in Node.js to perform AES decryption in ECB mode. It takes in a key and the encrypted text (in base64-encoded format), and returns the decrypted text. Note that we need to use the same key and mode of operation (ECB) in both the Python and JavaScript functions.
🌐
Python Forum
python-forum.io › thread-36432.html
Encrypt and decrypt in python using own fixed key
Hi I want to encrypt an d decrypt. But I want to use fixed defined key for example: key = 'Abcd123'. Can some one help how to do it. Thanks in advance. I use below code. from cryptography.fernet import Fernet message = 'I am python' key = Fernet.gen...