python - How to decrypt using Blowfish in Pycrypto? -
i found 1 example encrypt data unable find example on how decrypt it.
encryption example:
>>> crypto.cipher import blowfish >>> crypto import random >>> struct import pack >>> >>> bs = blowfish.block_size >>> key = b'an arbitrarily long key' >>> iv = random.new().read(bs) >>> cipher = blowfish.new(key, blowfish.mode_cbc, iv) >>> plaintext = b'docendo discimus ' >>> plen = bs - divmod(len(plaintext),bs)[1] >>> padding = [plen]*plen >>> padding = pack('b'*plen, *padding) >>> msg = iv + cipher.encrypt(plaintext + padding)
i did not find example on how decrypt.
let's make observations:
- cbc mode needs initialization vector (iv) has same length block size
- the full plaintext actual message including padding (pkcs#5 padding in rfc 2898 sec. 6.1.1 step 4)
- the iv prepended ciphertext
what needs done:
- use same key
- read iv before creating decryptor
- remove padding after decryption looking @ last byte, evaluate integer , remove many bytes end of plaintext
code:
from crypto.cipher import blowfish struct import pack bs = blowfish.block_size key = b'an arbitrarily long key' ciphertext = b'\xe2:\x141vp\x05\x92\xd7\xfa\xb5@\xda\x05w.\xaarg+u+\xc5g\x08\xdf\xf4xua\x88\x1b' iv = ciphertext[:bs] ciphertext = ciphertext[bs:] cipher = blowfish.new(key, blowfish.mode_cbc, iv) msg = cipher.decrypt(ciphertext) last_byte = msg[-1] msg = msg[:- (last_byte if type(last_byte) int else ord(last_byte))] print(repr(msg))
Comments
Post a Comment