What is the method for encrypting strings in Python?

Common encryption methods for strings in Python include:

  1. Hash encryption can be performed using the hashlib module, with algorithms such as MD5, SHA-1, and SHA-256. Sample code:
import hashlib

text = "Hello, World!"
hashed_text = hashlib.md5(text.encode()).hexdigest()
print(hashed_text)
  1. Encode the data using the base64 module.
    Example code:
import base64

text = "Hello, World!"
encoded_text = base64.b64encode(text.encode()).decode()
print(encoded_text)
  1. Make use of the cryptography module for symmetric or asymmetric encryption.
    Sample code:
from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)

text = "Hello, World!"
encrypted_text = cipher.encrypt(text.encode())
print(encrypted_text)

decrypted_text = cipher.decrypt(encrypted_text).decode()
print(decrypted_text)

There are several common encryption methods listed above, the specific choice of method depends on the encryption needs and security requirements.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds