python怎么对字符串加密解密

avatar
作者
筋斗云
阅读量:0

Python中可以使用多种方法对字符串进行加密解密,以下是其中一种常见的方法:

  1. 使用base64模块进行加密解密:
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) 

输出结果:

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

以上代码使用了base64编码方法进行加密解密。在加密过程中,首先将字符串编码为bytes类型,然后使用base64模块的b64encode方法进行编码,并将结果转换为字符串类型;在解密过程中,先将字符串转换为bytes类型,然后使用base64模块的b64decode方法进行解码,并将结果转换为字符串类型。

需要注意的是,base64编码并不属于加密算法,它只是一种编码方式,可以将二进制数据转换为可读的字符串形式。因此,base64编码的结果是可以被解码还原回原始数据的。如果需要更高级别的加密算法,可以考虑使用其他模块或库,如cryptographypycryptodome等。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!