How to Encrypt and Decrypt a String in Python

Simple way to encode a string according to a password?

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.

using function to encrypt/decrypt a string

It seems like what you want is a caesar cipher which is relatively simple to do in python.

def encrypt(text, key):
"""Encrypts text using a ceaser cypher"""
encrypted = ""
for char in text:
if char.isalpha():
encrypted += chr((ord(char) + key - 97) % 26 + 97)
else:
encrypted += char
return encrypted

The only really weird part about this code is the unicode character madness. If you don't know unicode/ascii is a way to map numbers in a computers memory to characters which computer memory is fundamentally just 1's and 0's. here's a chart for all the relevant character

https://www.asc.ohio-state.edu/demarneffe.1/LING5050/material/ASCII-Table.png

How to encrypt and decrypt a string with a password with python

Check out https://pypi.org/project/pycrypto/

Example from the site (which seems to be what you need):

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

how to decrypt a string that is encrypted using XOR

The algorithm does not perform a pure XOR, but maps values conditionally to another value, leading to a relation that is no longer bijective.

To illustrate this point. See what this script outputs:

keyword = "MELLON"
print(xor("Onions", keyword) == xor("OTGEHs", keyword))

It will output True!

So this means you have two words that are encrypted to the same string. This also means that if you need to do the reverse, there is no way to know which of these is the real original word.

If you want to decryption to be possible, make sure to only use operations that lead to a bijective mapping. For instance, if you only use a XOR, without adding or subtracting values, it will be OK.

Here is an approach where only lower and uppercase letters of the Latin alphabet are allowed (for both arguments):

def togglecrypt(string, key):
mapper = "gUMtuAqhaEDcsGjBbreSNJYdFTiOmHKwnXWxzClQLRVyvIkfPpoZ"

res = []
for i, ch in enumerate(string):
shift = mapper.index(key[i % len(key)]) % 26
i = mapper.index(ch)
if i < 26:
j = 26 + (i + shift) % 26
else:
j = (i - shift) % 26
res.append(mapper[j])
return("".join(res))

keyword = "MELLON"
encoded = togglecrypt("Onions", keyword)
print(encoded) # TdsDAn
print(togglecrypt(encoded, keyword)) # Onions

How to encrypt a string using python Openssl public key?

The documentation recommends that you call key.to_cryptography_key() to get a cryptographic key, and then use pyca/cryptography to perform the encryption.

https://www.pyopenssl.org/en/stable/api/crypto.html

Given your crypto key:

result = crypto_key.encrypt(b"Hello there")

I should add, RSA is primary intended for signatures and verification, and key exchange. It's way too slow for general encryption.



Related Topics



Leave a reply



Submit