1.安装Cryptodome 库
pip install pycryptodome
Base64
import base64 def base64_encode(text): encode_data = base64.b64encode(text.encode()) return encode_data def base64_decode(encode_data): decode_data = base64.b64decode(encode_data) return decode_data if __name__ == '__main__': text = 'base64加密解密' encode_data = base64_encode(text) decode_data = base64_decode(encode_data) print('Base64 编码:', encode_data) print('Base64 解码:', decode_data)
MD5
import hashlib def md5_encode(data): encode_data = hashlib.md5(data.encode()) encode_text = encode_data.hexdigest() return encode_text if __name__ == '__main__': data = "MD5加密" encode_text = md5_encode(data) print(encode_text)
PBKDF2
import binascii from Cryptodome.Hash import SHA1 from Cryptodome.Protocol.KDF import PBKDF2 def pbkdf2_encrypt(text, salt): result = PBKDF2(text, salt, count=10, hmac_hash_module=SHA1) result = binascii.hexlify(result).decode() return result if __name__ == '__main__': text = 'PBKDF2' salt = b'123456' result = pbkdf2_encrypt(text=text, salt=salt) print(result)
SHA系列(sha256为例)
from hashlib import sha256 def encrypt(text): encrypt_text = sha256(text.encode()) #encrypt_text = sha1(text.encode()) # encrypt_text = sha224(text.encode()) # encrypt_text = sha384(text.encode()) # encrypt_text = sha512(text.encode()) return encrypt_text.hexdigest() if __name__ == '__main__': text = "SHA256" print(encrypt(text))
AES
import base64 from Crypto.Cipher import AES def pad_16(value): count = len(value) if (count % 16 != 0): add = 16 - (count % 16) else: add = 0 text = value + ("\0".encode() * add) return text def aes_encrypt(key, t, iv): aes = AES.new(pad_16(key), AES.MODE_CBC, pad_16(iv)) encrypt_aes = aes.encrypt(pad_16(t)) encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8') return encrypted_text def aes_decrypt(key, t, iv): aes = AES.new(pad_16(key), AES.MODE_CBC, pad_16(iv)) base64_decrypted = base64.decodebytes(t.encode(encoding='utf-8')) decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '') return decrypted_text if __name__ == '__main__': key = "shzxsjicommunity".encode() text = "AES加密".encode() iv = "shzxsjicommunity".encode() encrypted_str = aes_encrypt(key, text, iv) print('加密:', encrypted_str) decrypted_str = aes_decrypt(key, encrypted_str, iv) print('解密:', decrypted_str)
RSA
import base64 from Cryptodome.PublicKey import RSA from Cryptodome.Cipher import PKCS1_v1_5 data = "cKK8B2rWwfwWeXhz" public_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM1xhOWaThSMpfxFsjV5YaWOFHt+6RvS+zH2Pa47VVr8PkZYnRaaKKy2MYBuEh7mZfM/R1dUXTgu0gp6VTNeNQkCAwEAAQ==" rsa_key = RSA.import_key(base64.b64decode(public_key)) cipher = PKCS1_v1_5.new(rsa_key) cipher_text = base64.b64encode(cipher.encrypt(data.encode(encoding="utf-8"))) print(cipher_text)
python 实现常见加密算法
最新推荐文章于 2024-02-03 10:09:30 发布