def encrypt_data(user_data: bytes) -> bytes: cipher = CBCCipher(FIXED_KEY, FIXED_IV) s = b"comment1=cooking%20MCs;userdata=" \ + user_data.replace(b";", b"").replace(b"=", b"") \ + b";comment2=%20like%20a%20pound%20of%20bacon" return cipher.encrypt(pad16_PKCS7(s))
def decrypt(self, bs: bytes) -> bytes: decrypted_chunks = [] # Encrypted chunks last = self.iv for i in range(0, len(pad16_PKCS7(bs)), 16): ciphertext_block = bs[i:i + 16] plain_chunk = xor(last, self.cipher.decrypt(ciphertext_block)) decrypted_chunks.append(plain_chunk) last = ciphertext_block return b''.join(decrypted_chunks)
def encrypt(self, plaintext: bytes) -> bytes: """ :param plaintext: message to be encrypted :return: encrypted byte string """ last = self.iv encrypted_chunks = [] # Encrypted chunks for i in range(0, len(pad16_PKCS7(plaintext)), 16): plaintext_block = plaintext[i:i + 16] e_chunk = self.cipher.encrypt(xor(last, plaintext_block)) encrypted_chunks.append(e_chunk) last = e_chunk return b''.join(encrypted_chunks)
def build(self) -> (BBoxType, bytes): prefix = os.urandom(randint(5, 10)) suffix = os.urandom(randint(5, 10)) test_data = pad16_PKCS7(self.test_data()) bbox_type = self.next_bbox_type() if bbox_type == BBoxType.ECB: cipher = AES.new(rand_n_string(16).encode(), AES.MODE_ECB) box_content = cipher.encrypt(test_data) elif bbox_type == BBoxType.CBC: cipher = CBCCipher( rand_n_string(16).encode(), rand_n_string(16).encode()) box_content = cipher.encrypt(test_data) else: raise NotImplemented("Cannot handle box type: " + str(bbox_type)) return bbox_type, prefix + box_content + suffix
def encrypt(plain_text: bytes) -> bytes: return cipher.encrypt(pad16_PKCS7(plain_text))
def cipher_text_provider() -> (bytes, bytes): p = pad16_PKCS7(FIXED_STRING) cipher = CBCCipher(FIXED_KEY, FIXED_IV) return FIXED_IV, cipher.encrypt(p)
def test_pad_1(self): pkcs_ = pad16_PKCS7(b"ICE ICE BABY") self.assertEqual(pkcs_, b"ICE ICE BABY\x04\x04\x04\x04")
def test_pad_0(self): pkcs_ = pad16_PKCS7(b"YELLOW SUBMARINE") self.assertEqual(pkcs_, b"YELLOW SUBMARINE\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10\x10")
def encrypt_(known_text: bytes, unknown_text: bytes) -> bytes: cipher = AES.new(FIXED_KEY, AES.MODE_ECB) box_content = cipher.encrypt(pad16_PKCS7(known_text + unknown_text)) return box_content