How to Encrypt Strings in Python

Configurare noua (How To)

Situatie

Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key.

Solutie

Pasi de urmat

We require a key for encryption. There are two main types of keys used for encryption and decryption. They are Symmetric-key and Asymmetric-key.

Symmetric-key Encryption:

In symmetric-key encryption, the data is encoded and decoded with the same key. This is the easiest way of encryption, but also less secure. The receiver needs the key for decryption, so a safe way need for transferring keys. Anyone with the key can read the data in the middle.

Install the python cryptography library with the following command.

pip install cryptography

Steps:

  • Import Fernet
  • Then generate an encryption key, that can be used for encryption and decryption.
  • Convert the string to a byte string, so that it can be encrypted.
  • Instance the Fernet class with the encryption key.
  • Then encrypt the string with the Fernet instance.
  • Then it can be decrypted with Fernet class instance and it should be instanced with the same key used for encryption.

from cryptography.fernet import Fernet

# we will be encrypting the below string.
message = “hello geeks”

# generate a key for encryption and decryption
# You can use fernet to generate
# the key or use random key generator
# here I’m using fernet to generate key

key = Fernet.generate_key()

# Instance the Fernet class with the key

fernet = Fernet(key)

# then use the Fernet class instance
# to encrypt the string string must
# be encoded to byte string before encryption
encMessage = fernet.encrypt(message.encode())

print(“original string: “, message)
print(“encrypted string: “, encMessage)

# decrypt the encrypted string with the
# Fernet instance of the key,
# that was used for encrypting the string
# encoded byte string is returned by decrypt method,
# so decode it to string with decode methods
decMessage = fernet.decrypt(encMessage).decode()

print(“decrypted string: “, decMessage)

Tip solutie

Permanent

Voteaza

(7 din 14 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?