我想了解PyCrypto如何在項目中使用,但我並不完全瞭解初始化向量(IV)的意義。我發現在解碼一個字符串時我可以使用錯誤的IV,並且除了前16個字節(塊大小)外,我似乎仍然收到消息。我只是使用它錯誤或不理解的東西?PyCrypto - 初始化矢量如何工作?
下面是一個示例代碼來演示:
import Crypto
import Crypto.Random
from Crypto.Cipher import AES
def pad_data(data):
if len(data) % 16 == 0:
return data
databytes = bytearray(data)
padding_required = 15 - (len(databytes) % 16)
databytes.extend(b'\x80')
databytes.extend(b'\x00' * padding_required)
return bytes(databytes)
def unpad_data(data):
if not data:
return data
data = data.rstrip(b'\x00')
if data[-1] == 128: # b'\x80'[0]:
return data[:-1]
else:
return data
def generate_aes_key():
rnd = Crypto.Random.OSRNG.posix.new().read(AES.block_size)
return rnd
def encrypt(key, iv, data):
aes = AES.new(key, AES.MODE_CBC, iv)
data = pad_data(data)
return aes.encrypt(data)
def decrypt(key, iv, data):
aes = AES.new(key, AES.MODE_CBC, iv)
data = aes.decrypt(data)
return unpad_data(data)
def test_crypto():
key = generate_aes_key()
iv = generate_aes_key() # get some random value for IV
msg = b"This is some super secret message. Please don't tell anyone about it or I'll have to shoot you."
code = encrypt(key, iv, msg)
iv = generate_aes_key() # change the IV to something random
decoded = decrypt(key, iv, code)
print(decoded)
if __name__ == '__main__':
test_crypto()
我使用Python 3.3。
輸出將在執行有所不同,但我得到的是這樣的:b"1^,Kp}Vl\x85\x8426M\xd2b\x1aer secret message. Please don't tell anyone about it or I'll have to shoot you."
好吧,我想我明白了......我想也許加密文本只會改變第一個塊,但它似乎影響到整個字節鏈。似乎通常的做法是在發送之前將IV加入加密的代碼中,所以我認爲我會這樣做。 –