0

Followed the example here: https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode

Also can decrypt in online encryption/decryption services.

My example is not working:

import hashlib
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad


def decipher():
    secret_key = 'secret key'
    secret_iv = 'secret iv'
    key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
    iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
    s = 'HNAQf+1/fZXxzGTdVUs1qg=='
    s = str.encode(s)
    cipher = AES.new(key, AES.MODE_CBC, iv=iv)

    plain_text = unpad(cipher.decrypt(s), AES.block_size) #<-- this line

    return plain_text

ValueError: Data must be padded to 16 byte boundary in CBC mode

Robb
  • 45
  • 1
  • 5
  • 1
    The ciphertext must be Base64 decoded before decryption: `s = b64decode(s) #str.encode(s)` – Topaco Jan 12 '23 at 10:33
  • Note that SHA-256 is not a good Key Derivation Function. As such the example should be considered insecure as the key can be easily guessed. There are other issues as well. – Maarten Bodewes Jan 12 '23 at 11:10
  • What would you sugest? – Robb Jan 12 '23 at 11:49
  • 3
    There are e.g. the following vulnerabilities: 1. Static IV, leading to reuse of key/IV pairs (for a fixed key). Instead, apply for each encryption a random IV which has to be passed along with the ciphertext to the decrypting side (usually concatenated). 2. key derivation with a fast hash, which makes an attack easier. Instead, use a dedicated (slow) key derivation function, at least PBKDF2 (or more modern algorithms like Argon2, scrypt etc.) 3. No data authentication. Instead, apply an HMAC for CBC or directly a mode for authenticated encryption (like GCM). – Topaco Jan 12 '23 at 12:56

0 Answers0