Tuesday, December 18, 2018

Encryption and Decryption in Python

In cryptography, encryption is the process of encoding the message that only authorized people can access it

Encryption is different from hashing, because the message need to be decrypted in encryption

So a key is required to decrypt and encrypt the message

In cryptography, Cipher is an algorithm used for encryption and decryption

Cipher requires a key. This key will be known by only two parties, sender and receiver

This allows transmission of message over public channels but it is only readable by intended parties

Let us install cryptography using PIP and see a demo
C:\Users\username>pip install cryptography

>>>
>>> from cryptography.fernet import Fernet
>>>
>>> key=Fernet.generate_key()
>>>
>>> cipher_send=Fernet(key)
>>> cipher_send.encrypt(b"Namaste")
b'gAAAAABcGZzS79dzaWvwOSTXFvQT0fn0e5v_bfoYh-bxlPHOC4DUR1eS0nM0S920hrSx8BkaIU4gQl2iKk4I2LiUu1M7wHyLTw=='
>>>

Now get the value of 'key' variable to decrypt the string back

>>> key
b'sW3O6ErXS_eJ829vLaSSkFhzn477btpu7yw_28-lUb8='
>>>

>>> cipher_reciever=Fernet(b'sW3O6ErXS_eJ829vLaSSkFhzn477btpu7yw_28-lUb8=')
>>> cipher_reciever.decrypt(b'gAAAAABcGZzS79dzaWvwOSTXFvQT0fn0e5v_bfoYh-bxlPHOC4DUR1eS0nM0S920hrSx8BkaIU4gQl2iKk4I2LiUu1M7wHyLTw==')
b'Namaste'
>>>

Now let us create our own key:

>>> import hashlib
>>> keyword=b"1234$"
>>> key=hashlib.sha3_256(keyword)
>>> key
<_sha3.sha3_256 object at 0x000001F6486339E0>

>>> key.digest()
b'\xd6\x96\xaf\xd5\xfe\x9f\xce7\x86\x12\xaa\xb1\xa7x\x93!+\xc2V\xb8\x11\x16\x94\x06P\xed-\x970N1I'
>>>

This is not in the format , that a fernet object expects, import module base64

>>> import base64
>>> key_bytes=key.digest()
>>> fernet_key=base64.urlsafe_b64encode(key_bytes)
>>> fernet_key
b'1pav1f6fzjeGEqqxp3iTISvCVrgRFpQGUO0tlzBOMUk='
>>>

Now using the custom key , let us encrypt and decrypt our strings

>>> cipher_custom=Fernet(fernet_key)
>>> cipher_custom.encrypt(b"welcome")
b'gAAAAABcGaLgE1MZX5bF-HE8HfWdcbkBI771mGr6GOan71tmcAlULuF0B7ZAkNbdZIVfF5CXU5xBzFTIh1o7IScxzNCRGmJkSQ=='

Now decrypt,

>>> cipher_custom.decrypt(b'gAAAAABcGaLgE1MZX5bF-HE8HfWdcbkBI771mGr6GOan71tmcAlULuF0B7ZAkNbdZIVfF5CXU5xBzFTIh1o7IScxzNCRGmJkSQ==')
b'welcome'
>>>






No comments:

Post a Comment