def test_pad(self): self.assertEqual(util.pkcs5_pad('Hello World'), 'Hello World\x05\x05\x05\x05\x05') self.assertEqual(util.pkcs7_pad('Hello World', 15), 'Hello World\x04\x04\x04\x04') with self.assertRaises(ValueError): util.pkcs7_pad('Hello', 256)
def aes_api_data_encrypt(data): """ 加密api数据 :param data: 字符串数据等 :return: base64数据 """ key = '!@#$%^&*()_+|%^&' iv = '!@#$%^&*()_+|%^&' pad_data = pkcs7_pad(data, 16) encryptor = Cipher(alg="aes_128_cbc", key=key, iv=iv, op=OP_ENCRYPT, padding=0) str = encryptor.update(pad_data) str = str + encryptor.final() base64str = base64.b64encode(str) return base64str
def test(): import os from M2Crypto.util import pkcs7_pad from Crypto.Cipher import AES teststring = 'The quick brown fox jumped over the lazy dog' class PadBuster(PaddingOracle): def oracle(self, data): _cipher = AES.new(key, AES.MODE_CBC, str(iv)) ptext = _cipher.decrypt(str(data)) plen = ord(ptext[-1]) padding_is_good = (ptext[-plen:] == chr(plen) * plen) if padding_is_good: return raise BadPaddingException padbuster = PadBuster() key = os.urandom(AES.block_size) iv = bytearray(os.urandom(AES.block_size)) print "Testing padding oracle exploit in DECRYPT mode" cipher = AES.new(key, AES.MODE_CBC, str(iv)) data = pkcs7_pad(teststring, blklen=AES.block_size) ctext = cipher.encrypt(data) decrypted = padbuster.decrypt(ctext, block_size=AES.block_size, iv=iv) print "Key: %r" % (key, ) print "IV: %r" % (iv, ) print "Plaintext: %r" % (data, ) print "Ciphertext: %r" % (ctext, ) print "Decrypted: %r" % (str(decrypted), ) print "\nRecovered in %d attempts\n" % (padbuster.attempts, ) assert decrypted == data, \ 'Decrypted data %r does not match original %r' % ( decrypted, data) print "Testing padding oracle exploit in ENCRYPT mode" cipher2 = AES.new(key, AES.MODE_CBC, str(iv)) encrypted = padbuster.encrypt(teststring, block_size=AES.block_size) decrypted = cipher2.decrypt(str(encrypted))[AES.block_size:] decrypted = decrypted.rstrip(decrypted[-1]) print "Key: %r" % (key, ) print "IV: %r" % (iv, ) print "Plaintext: %r" % (teststring, ) print "Ciphertext: %r" % (str(encrypted), ) print "Decrypted: %r" % (str(decrypted), ) print "\nRecovered in %d attempts" % (padbuster.attempts, ) assert decrypted == teststring, \ 'Encrypted data %r does not decrypt to %r, got %r' % ( encrypted, teststring, decrypted)