Cipher with a key in Python | Assignment Expert

  • Cipher means an algorithm that can be used to encrypt or decrypt messages or sentences.
  • Encrypt means converting a message to a secret form that can not be understood by an unknown person.
  • Decrypt means converting an encrypted message back to its normal form.
  • Key is a text which is used with the message we want to encrypt/decrypt.

A cipher(algorithm) can be of 2 types based on symmetricity:

  • Symmetric key Cipher: These types of ciphers require the same key for encryption and decryption.
    • message => Encipher(message, key) => ciphered text => Decipher(ciphered text, key) => original message
  • Asymmetric Key Cipher: These types of ciphers use different types of keys for encryption and decryption.
    • message => Encipher(message, key1) => ciphered text => Decipher(ciphered text, key2) => original message

Code to encrypt using a cipher with a key in Python:

# importing AES
from Crypto.Cipher import AES

# encryption key
key = b'C&F)H@McQfTjWnZr'

# create new instance of cipher
cipher = AES.new(key, AES.MODE_EAX)

# data to be encrypted
data = "Welcome to violet-cat-415996.hostingersite.com!".encode()

# nonce is a random value generated each time we instantiate the cipher using new()
nonce = cipher.nonce

# encrypt the data
ciphertext = cipher.encrypt(data)

# print the encrypted data
print("Cipher text:", ciphertext)

Output:

Output to encrypt using a cipher with a key in Python

Code to decrypt using a cipher with a key in Python:

# generate new instance with the key and nonce same as encryption cipher
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)

# decrypt the data
plaintext = cipher.decrypt(ciphertext)
print("Plain text:", plaintext)

Output:

Output to decrypt using a cipher with a key in Python

Also Read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@violet-cat-415996.hostingersite.com Thank you