Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Two-way Alphanumeric Encryption

I am using Python 2.7. I have an alphanumeric string, on which I want to perform a encryption/decryption. Whatever I do should remain 2-way and the result should be alphanumeric too.

For example:

str = 'ma6546fbd'
encrypted_data = encrypt_function(str)
decrypted_data = decrypt_function(encrypted_data)
print decrypted_data # I get 'ma6546fbd'

What have I done:

I have written a function

def xor_crypt_string(data, key):
    return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))

This takes the data and a key and returns the result, the problem is that it includes special characters too, which I want to avoid.

like image 655
Zain Khan Avatar asked Jun 21 '12 06:06

Zain Khan


People also ask

What is Caesar Cipher in Python?

Caesar Cipher Technique is the simple and easy method of encryption technique. It is simple type of substitution cipher. Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.

How does Fernet encryption work?

When a user wants to encrypt a message with fernet, the recipe takes the plaintext message, a key and a timestamp as inputs, and then uses this information to produce a token. The token includes an encrypted version of the plaintext message, as well as the information needed to verify the integrity of the message.


1 Answers

If you want serious encryption (read unbreakable) then I'd use AES from pycrypto something like this.

>>> from Crypto.Cipher import AES
>>> from Crypto import Random
>>> key = b'Sixteen byte key'
>>> iv = Random.new().read(AES.block_size)
>>> cipher = AES.new(key, AES.MODE_CFB, iv)
>>> msg = iv + cipher.encrypt(b'Attack at dawn')
>>> msg.encode("hex")
'e10e096aabff9db382abe8d704404995a7b64d72a4e1b9e5208912d206c4'

That is your ascii message. Now decode the message like this

>>> recv='e10e096aabff9db382abe8d704404995a7b64d72a4e1b9e5208912d206c4'
>>> cipher.decrypt(recv.decode("hex"))[len(iv):]
'Attack at dawn'
>>> 

Any encryption method you make up yourself will be easily breakable by an expert and the one you've shown above falls into that category.

like image 57
Nick Craig-Wood Avatar answered Oct 08 '22 03:10

Nick Craig-Wood