Yılmaz Alpaslan
Yılmaz Alpaslan

Reputation: 359

(Python) How to decode aes.encrypt encoded cipher texts?

I am making an encyrption program with Python 3.7.9 and I started learning pycryptodome library and AES encryption but when I encrypt a plain text it gives me this: b'Q\xd7\x05\x0e\xa0\xea\x06b\xefVt' and I cannot decode it to string. When I try to decode it with cipher.decode('utf-8') it gives me this error:

Traceback (most recent call last):
  File "c:/Users/ymzym/OneDrive/Python Projects/Encrypt'n'Decrypt/test.py", line 25, in <module>
    print("Encrypted text:",cipher.decode("utf-8"))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9a in position 1: invalid start byte

And when I try to decode it with cipher.decode('latin-1') it outputs a weird thing: 8ê{ÊÚ´ã. How can I decode this?

Here is my code:

from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
import base64, os, binascii

def encrypt(key, plaintext):
    iv = Random.new().read(AES.block_size)
    iv_int = int(binascii.hexlify(iv), 16) 
    ctr = Counter.new(AES.block_size * 8, initial_value=iv_int)
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    ciphertext = aes.encrypt(plaintext)
    return ciphertext

key = base64.urlsafe_b64encode(os.urandom(22)) #Creates a 32 bytes AES-256 key
cipher = encrypt(key, b"Hello world")
print("Encrypted text:",cipher.decode('latin-1'))

Upvotes: 1

Views: 3095

Answers (1)

Michael Fehr
Michael Fehr

Reputation: 6414

For Base64 encoding and decoding I'm using this two functions:

import base64

def base64Encoding(input):
  dataBase64 = base64.b64encode(input)
  dataBase64P = dataBase64.decode("UTF-8")
  return dataBase64P

def base64Decoding(input):
    return base64.decodebytes(input.encode("ascii"))

so on encryption side the code would be:

ciphertext = base64Encoding(aes.encrypt(plaintext))

On decryption side you decode like this

ciphertext = base64Decoding(receivedCiphertext)

Upvotes: 3

Related Questions