x-terior
x-terior

Reputation: 1

Python, why does decrypt fails the second time

Below is a test. When I try to decode the same string for the second time I get a error message and I really have no clue why or where to search for. Please advise.

Error:

Traceback (most recent call last):
  File "test.py", line 28, in <module>
    telnr_to_string = str(telnr_decrypt, 'utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9e in position 0: invalid start byte

Code:

from Crypto.Cipher import AES
from Crypto.Util.Padding import *
from urllib.request import urlopen

import os
import urllib
import subprocess
import re
import time
import base64
import random
file_key = open("key.txt")
key = file_key.read()
key = key.encode()
file_iv = open("iv.txt")
iv = file_iv.read()
iv = iv.encode()
obj2 = AES.new(key, AES.MODE_CBC, iv)
z=1
while z < 3:
    x=''
    telnr_decrypt=''
    telnr=''
    telnr_to_string=''
    telnr_cleaned=''
    x=(b'\x9e\xde\x98p:\xa3\x04\x92\xb5!2K[\x8e\\\xee')
    telnr_decrypt = obj2.decrypt(x)
    telnr_to_string = str(telnr_decrypt, 'utf-8')
    telnr_cleaned = re.sub("[^0-9]", "", telnr_to_string)
    print (telnr_cleaned)
    z=z+1

Upvotes: 0

Views: 151

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

Just move obj2 = AES.new(key, AES.MODE_CBC, iv) into the while loop. Don't worry, cipher objects are not very stateful objects; they don't do much other than to store the key (or, for AES, probably the internal subkeys) and maintain a small buffer. Generally it is therefore a bad idea to reuse or cache them.

If you call encrypt / decrypt multiple times in succession then the methods act as if you would be encrypting one big message. In other words, they allow you to encryption / decrypt in a piecemeal fashion so that message-sized buffers can be avoided. This is not very explicitly documented, but you can see this in figure 2 in the documentation.

For CBC mode it means that the operation is identical to setting the IV to the last block of ciphertext. If the IV is wrong then the first block of plaintext will be randomized. Random bytes do generally not contain valid UTF-8 encoding, which means that decoding to string will (likely) fail.

Upvotes: 1

Related Questions