Commit ff7c0544 authored by Daniel Hofmann's avatar Daniel Hofmann
Browse files

Round robin encryption decryption validation

parent 71925e57
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# notes:
# - deps: pip install -r requirements.txt
# - keep it clean: flake8
from __future__ import print_function, division, with_statement # welcome to the future from __future__ import print_function, division, with_statement # welcome to the future
import argparse import argparse
...@@ -42,17 +46,38 @@ def main(): ...@@ -42,17 +46,38 @@ def main():
aes = aes_cipher(cfg['key'], cfg['iv']) aes = aes_cipher(cfg['key'], cfg['iv'])
next_mult = lambda x, n: n + (x - n % x) if n % x else n # PKCS#7 padding, see: 10.3/2 http://tools.ietf.org/html/rfc2315, http://stackoverflow.com/a/14205319
fill = (next_mult(AES.block_size, len(cfg['in'])) - len(cfg['in'])) * '0' pkcs7 = lambda bs, x: x + (bs - len(x) % bs) * chr(bs - len(x) % bs)
pad = cfg['in'] + fill unpkcs7 = lambda x: x[0:-ord(x[-1])]
padded = pkcs7(AES.block_size, cfg['in'])
assert(len(padded) % AES.block_size == 0), 'padded plaintext is not a multiple of block size'
assert(unpkcs7(padded) == cfg['in']), 'unpadding does not reverse padding'
enc = cfg['iv'] + aes.encrypt(pad) # encrypt: iv + aes(in + pkcs7_pad)
enc = cfg['iv'] + aes.encrypt(padded)
b64 = base64.b64encode(enc) b64 = base64.b64encode(enc)
logging.info('{0}'.format({'padded': pad, 'base64': b64})) logging.info('{0}'.format({'padding': len(padded), 'base64': b64}))
print(b64) print(b64)
# XXX: from here on: encryption validation
# decrypt: first AES.block_size is iv, rest is aes(in + pad)
raw = base64.b64decode(b64)
assert(len(raw) % AES.block_size == 0), 'encoded ciper text is not a multiple of block size'
iv, padded = raw[:AES.block_size], raw[AES.block_size:]
assert(iv == cfg['iv']), 'decoded iv mismatch'
assert(iv + padded == enc), 'decoded cipher mismatch'
logging.info('{0}'.format({'key': cfg['key'], 'iv': iv}))
aes = aes_cipher(cfg['key'], iv)
dec = unpkcs7(aes.decrypt(padded))
assert(cfg['in'] == dec), 'encryption decryption round robin mismatch'
if __name__ == '__main__': if __name__ == '__main__':
main() main()
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment