How to encrypt and decrypt strings in Python?

There are various methods available in Python for encrypting and decrypting strings, one common method is as follows:

  1. Encrypt and decrypt using the base64 module:
import base64

# 加密字符串
def encrypt_string(text):
    encrypted_text = base64.b64encode(text.encode()).decode()
    return encrypted_text

# 解密字符串
def decrypt_string(encrypted_text):
    decrypted_text = base64.b64decode(encrypted_text.encode()).decode()
    return decrypted_text

# 测试
text = "Hello, World!"
encrypted_text = encrypt_string(text)
decrypted_text = decrypt_string(encrypted_text)

print("原始字符串:", text)
print("加密后的字符串:", encrypted_text)
print("解密后的字符串:", decrypted_text)

Output result:

原始字符串: Hello, World!
加密后的字符串: SGVsbG8sIFdvcmxkIQ==
解密后的字符串: Hello, World!

The code above utilizes base64 encoding method for encryption and decryption. During the encryption process, the string is first encoded into bytes type, then encoded using the b64encode method of the base64 module, and the result is converted into a string type; during the decryption process, the string is first converted into bytes type, then decoded using the b64decode method of the base64 module, and the result is converted into a string type.

It should be noted that base64 encoding is not a encryption algorithm, it is just a way of encoding that can convert binary data into readable string form. Therefore, the result of base64 encoding can be decoded and restored back to the original data. If a higher level of encryption algorithm is needed, consider using other modules or libraries such as cryptography, pycryptodome, etc.

bannerAds