我今天刚刚找到pycrypto,我一直在研究我的AES加密类。不幸的是,它只起了一半的作用。self.h。Md5输出Md5哈希值,格式为十六进制,长度为32字节。这是输出。它似乎解密消息,但它在解密后放入随机字符,在这种情况下nnn…我想我对自我的块大小有问题。数据,有人知道怎么解决这个问题吗?
jan - macbook - pro:test2 jan$ ../../bin/python3 data.pyb 'RLfGmn5jf5WTJphnmW0hXG7IaIYcCRpjaTTqwXR6yiJCUytnDib + GQYlFORm + jIctest1 2 3 4 5 endtestnnnnnnnnnn nnnn'
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
from os import urandom
class Encryption():
def __init__(self):
self.h = Hash()
def values(self, data, key):
self.data = data
self.key = key
self.mode = AES.MODE_CBC
self.iv = urandom(16)
if not self.key:
self.key = Cfg_Encrypt_Key
self.key = self.h.md5(self.key, True)
def encrypt(self, data, key):
self.values(data, key)
return b64encode(self.iv + AES.new(self.key, self.mode, self.iv).encrypt(self.data))
def decrypt(self, data, key):
self.values(data, key)
self.iv = b64decode(self.data)[:16]
return AES.new(self.key, self.mode, self.iv).decrypt(b64decode(self.data)[16:])
老实说,字符"nnnnnnnnnn nnnnn"在我看来并不是那么随机。: -)
您在CBC模式下使用AES。这要求明文和密文的长度始终是16字节的倍数。使用您所展示的代码,您实际上应该看到,当传递给encrypt()
的data
不满足这些条件时,会引发异常。看起来您添加了足够的新行字符('n'),无论输入是什么,直到明文碰巧对齐。
从CBC (
AES.MODE_CBC
)切换到CFB (AES.MODE_CFB
)。PyCrypto使用默认的segment_size
,您将不会对明文和密文长度有任何限制。保留CBC并使用pkcs# 7之类的填充方案,即:
在加密
X
字节的明文之前,在后面添加您需要达到下一个16字节边界的多少字节。所有填充字节具有相同的值:您正在添加的字节数:length = 16 - (len(data) % 16) data += bytes([length])*length
这是Python 3的风格。在Python 2中,你可以这样写:
length = 16 - (len(data) % 16) data += chr(length)*length
解密后,从明文的后面删除尽可能多的字节填充:
data = data[:-data[-1]]
尽管我明白在你的情况下,这只是一个类练习,我想指出,它是不安全的发送数据没有任何形式的身份验证(例如MAC)。
只要记住初始有效负载的长度,就可以使用固定字符,这样就不会"丢掉"有用的结束字节。试试这个:
import base64
from Crypto.Cipher import AES
def encrypt(payload, salt, key):
return AES.new(key, AES.MODE_CBC, salt).encrypt(r_pad(payload))
def decrypt(payload, salt, key, length):
return AES.new(key, AES.MODE_CBC, salt).decrypt(payload)[:length]
def r_pad(payload, block_size=16):
length = block_size - (len(payload) % block_size)
return payload + chr(length) * length
print(decrypt(encrypt("some cyphertext", "b" * 16, "b" * 16), "b" * 16, "b" * 16, len("some cyphertext")))
from hashlib import md5
from Crypto.Cipher import AES
from Crypto import Random
import base64
def derive_key_and_iv(password, salt, key_length, iv_length):
d = d_i = ''
while len(d) < key_length + iv_length:
d_i = md5(d_i + password + salt).digest()
d += d_i
return d[:key_length], d[key_length:key_length+iv_length]
def encrypt(in_file, out_file, password, key_length=32):
bs = AES.block_size
salt = Random.new().read(bs - len('Salted__'))
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
#print in_file
in_file = file(in_file, 'rb')
out_file = file(out_file, 'wb')
out_file.write('Salted__' + salt)
finished = False
while not finished:
chunk = in_file.read(1024 * bs)
if len(chunk) == 0 or len(chunk) % bs != 0:
padding_length = bs - (len(chunk) % bs)
chunk += padding_length * chr(padding_length)
finished = True
out_file.write(cipher.encrypt(chunk))
in_file.close()
out_file.close()
def decrypt(in_file, out_file, password, key_length=32):
bs = AES.block_size
in_file = file(in_file, 'rb')
out_file = file(out_file, 'wb')
salt = in_file.read(bs)[len('Salted__'):]
key, iv = derive_key_and_iv(password, salt, key_length, bs)
cipher = AES.new(key, AES.MODE_CBC, iv)
next_chunk = ''
finished = False
while not finished:
chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))
if len(next_chunk) == 0:
padding_length = ord(chunk[-1])
if padding_length < 1 or padding_length > bs:
raise ValueError("bad decrypt pad (%d)" % padding_length)
# all the pad-bytes must be the same
if chunk[-padding_length:] != (padding_length * chr(padding_length)):
# this is similar to the bad decrypt:evp_enc.c from openssl program
raise ValueError("bad decrypt")
chunk = chunk[:-padding_length]
finished = True
out_file.write(chunk)
in_file.close()
out_file.close()
def encode(in_file, out_file):
in_file = file(in_file, 'rb')
out_file = file(out_file, 'wb')
data = in_file.read()
out_file.write(base64.b64encode(data))
in_file.close()
out_file.close()
def decode(in_file, out_file):
in_file = file(in_file, 'rb')
out_file = file(out_file, 'wb')
data = in_file.read()
out_file.write(base64.b64decode(data))
in_file.close()
out_file.close()
AES.new().encrypt()
和.decrypt()
均取长度为16的倍数的字符串作为输入和输出。你必须用这样或那样的方法来解决它。例如,您可以在开始时存储实际长度,并使用它来截断解密字符串。
还请注意,虽然它是AES的唯一限制,但其他模块(特别是在Crypto.PublicKey
中)有来自其数学实现的额外限制,并且不应该(在我看来)对最终用户可见,但它们是可见的。例如,Crypto.PublicKey.ElGamal
将加密任何短字符串,但如果它以空字符开头,则在解密时它们将丢失。