33
loading...
This website collects cookies to deliver better user experience
cryptography: It includes both high level recipes and low-level interfaces to common cryptographic algorithms such as symmetric ciphers, message digests, and key derivation functions. We will be using it for demonstration of symmetric key cryptography.
rsa: It include pure implementation of rsa algorithm. We will be using it for demonstration of asymmetric key cryptography.
haslib: It provides interface for hashing messages easily. It contains numerous methods which will handle hashing any raw message in an encrypted format. We will be using it for demonstration of hashing.
pip install cryptography
pip install rsa
python -m pip install --upgrade pip
from cryptography.fernet import Fernet
plain_text = "Hello World"
# generating random key
key = Fernet.generate_key()
# creating object of Fernet class
fernet = Fernet(key)
# encryption takes place using encrypt method
cipher = fernet.encrypt(plain_text.encode())
print("original string: ", plain_text)
print("encrypted string: ", cipher)
# decryption takes place using decrypt method
newMessage = fernet.decrypt(cipher).decode()
print("decrypted string: ", newMessage)
original string: Hello World
encrypted string: b'gAAAAABhVfD58m85tEJe3U4AQRbhIXFULXdfFGZnzS7IHS6aH8VGC4il3HSTF2tMjQ7_WJJdUAcAHuNV27ravfvOFOPv1hsQYg=='
decrypted string: Hello World
import rsa
#newkeys method will generate both the keys
public_key, private_key = rsa.newkeys(512)
plain_text = "Hello World"
#encryption takes place using encrypt method using public key
#normal string should be encoded into byte string
#using encode method
cipher = rsa.encrypt(plain_text.encode(),public_key)
print("original string: ", plain_text)
print("encrypted string: ", cipher)
#decryption takes place using decrypt method using private key
#after that string is converted from byte stream to string
#using decode method
newMessage = rsa.decrypt(cipher, private_key).decode()
print("decrypted string: ", newMessage)
original string: Hello World
encrypted string: b')e`\x00\xd7\xdb\xce\xae)\x93 \x06\x8b\x9a\x08\x90\xca`\xbd\x0e\xcc>72$\x08_\x0b\x9a6\x93\xf8\xc4\x1f\x8cv\xf7\xd1\x8e\x84\xb4\xd0\xb1\nPj\xee\xc5\x14\x88B\xd4{\x89[%\xab}s\xdcY\x05\x93\xba'
decrypted string: Hello World
import hashlib
plain_text = "Hello World"
#MD5 Hashing takes place
md5Hash = hashlib.md5(plain_text.encode())
#Hexidecimal string is generated
hexValue1 = md5Hash.hexdigest()
print("MD5 Hash Value:",hexValue1)
#SHA Hashing takes place
shaHash = hashlib.sha1(plain_text.encode())
#Hexidecimal string is generated
hexValue2 = shaHash.hexdigest()
print("SHA Hash Value:",hexValue2)
MD5 Hash Value: b10a8db164e0754105b7a99be72e3fe5
SHA Hash Value: 0a4d55a8d778e5022fab701977c5d840bbc486d0