我已经为 编写了一些抽象Crypto.Cipher.AES.encrypt/decrypt
,我想为它编写单元测试。编写单元测试decrypt
很容易,但是有没有合理的方法来测试加密本身是否发生?例如,有没有办法查看一个字节串并知道是的,那是一块 AES 加密数据?如果不是(也许这会泄露太多信息),我有什么选择来测试我的encrypt
函数是否具有合理的输出?
def encrypt(plaintext):
"""Return 'plaintext' AES encrypted."""
initialization_vector = Random.new().read(AES.block_size)
cipher = AES.new(settings.secret, AES.MODE_CFB, initialization_vector)
return initialization_vector + cipher.encrypt(bytes(plaintext.encode('utf-8')))
def decrypt(crypt):
"""Return 'crypt' AES decrypted."""
initialization_vector, crypt = crypt[:AES.block_size], crypt[AES.block_size:]
cipher = AES.new(settings.secret, AES.MODE_CFB, initialization_vector)
return cipher.decrypt(crypt)
# … this is a method of a unittest.TestCase subclass:
def test_decrypt(self):
"""Test that a message can be decrypted."""
crypt = utils.encrypt("abcdefg")
decrypt = utils.decrypt(crypt)
self.assertEqual("abcdefg", decrypt)
def test_encrypt(self):
"""Test that a message can be encrypted. … if you can"""
crypt = utils.encrypt("abcdefg")
self.assertSomethingmumblemumble(crypt)