在Python中加密输入参数可以通过多种方式实现,以下是几种常见的加密方法:
1. Base64编码
Base64编码是一种将二进制数据转换为ASCII字符的方法,常用于数据传输或存储。
import base64待加密数据data = "hello world"编码encoded_data = base64.b64encode(data.encode('utf-8'))print(encoded_data) 输出:b'aGVsbG8gd29ybGQ='解码decoded_data = base64.b64decode(encoded_data).decode('utf-8')print(decoded_data) 输出:hello world
2. MD5加密
MD5是一种不可逆的散列算法,用于生成数据的固定长度的摘要。
import hashlib待加密数据data = "中国你好"创建MD5对象md5_hash = hashlib.md5()对数据进行加密md5_hash.update(data.encode('utf-8'))获取加密后的摘要encrypted_data = md5_hash.hexdigest()print(encrypted_data) 输出:MD5加密后的摘要
3. 自定义加密规则
可以自定义加密规则对输入参数进行加密。
def custom_encrypt(text):map_dict = {'1': '1', 'abc': '2', 'def': '3', 'ghi': '4', 'jkl': '5', 'mno': '6', 'pqrs': '7', 'tuv': '8', 'wxyz': '9', '0': '0'}encrypted_text = ""for char in text:if 'A' <= char <= 'Z':encrypted_text += chr((ord(char) - ord('A') + 3) % 26 + ord('A'))elif 'a' <= char <= 'z':encrypted_text += map_dict.get(char, char)else:encrypted_text += charreturn encrypted_text待加密数据data = "Hello World"加密encrypted_data = custom_encrypt(data)print(encrypted_data) 输出:加密后的文本
4. 对称加密
对称加密使用相同的密钥进行加密和解密,例如AES。
from cryptography.fernet import Fernet生成密钥key = Fernet.generate_key()创建Fernet对象cipher_suite = Fernet(key)待加密数据data = "hello world"加密encrypted_data = cipher_suite.encrypt(data.encode('utf-8'))print(encrypted_data) 输出:加密后的数据解密decrypted_data = cipher_suite.decrypt(encrypted_data).decode('utf-8')print(decrypted_data) 输出:解密后的数据
5. 非对称加密
非对称加密使用一对密钥,包括公钥和私钥,例如RSA。
from cryptography.hazmat.primitives.asymmetric import rsafrom cryptography.hazmat.primitives import serialization生成密钥对private_key = rsa.generate_private_key(public_exponent=65537,key_size=2048,)public_key = private_key.public_key()待加密数据data = "hello world"使用公钥加密encrypted_data = public_key.encrypt(data.encode('utf-8'),padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))print(encrypted_data) 输出:加密后的数据使用私钥解密decrypted_data = private_key.decrypt(encrypted_data,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(),label=None))print(decrypted_data.decode('utf-8')) 输出:解密后的数据
选择合适的
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/83517.html