在Python中,可以使用pycrypto工具包来实现比特流加密。具体方法如下:
1.安装pycrypto
pip install pycrypto
2.代码示例:
from Crypto.Cipher import AES import base64
def aes_encrypt(key, text): length = 16 text = text.encode('utf-8') num = length - (len(text) % length) text = text + (chr(num) * num).encode('utf-8') cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB) encrypted_text = cipher.encrypt(text) return base64.b64encode(encrypted_text)
def aes_decrypt(key, text): text = base64.b64decode(text) cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB) decrypted_text = cipher.decrypt(text).decode('utf-8') decrypted_text = decrypted_text[:-ord(decrypted_text[-1])] return decrypted_text
text = "hello world" key = "key" encrypted_text = aes_encrypt(key, text) print(encrypted_text) decrypted_text = aes_decrypt(key, encrypted_text) print(decrypted_text)
输出结果:
b'tZvjRHWgS+uZiR2zHP+T1A==' hello world
说明:上述代码中采用的是AES加密算法和ECB模式,加密key为字符串类型,需要转为bytes类型才能进行加解密操作。加密后的密文为bytes类型,需要用base64进行编码转为字符串类型输出。
上一篇:比特流混淆问题。