0

I wish, using Python3's Crypto.Cipher to use AES in CTR mode. The actual problem is that I have an array of binary digits ( "0/1" in string format ) and that I wish to encrypt/decrypt them using the AES-CTR. After viewing this article I tried to develop the code that is appended below.

from Crypto.Cipher import AES
import os
import sys

secret = os.urandom(16)
crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=lambda: secret)

msg = "Hello World"

#string-->bytes
bytes_msg = str.encode(msg)
print(msg + " > 2bytes > " + str(bytes_msg))

#bytes-->encrypt
encrypted_bytes_msg = crypto.encrypt(bytes_msg)
print(" > encryption > " + str(encrypted_bytes_msg))

#encrypt-->decrypt
decrypted_bytes_msg = crypto.decrypt(encrypted_bytes_msg)
print(" > decryption > " + str(decrypted_bytes_msg))

#bytes-->string
#decrypted_msg = decrypted_bytes_msg.decode() # <= !ERROR HERE!
#print(" > msg > " + decrypted_msg)

I was expecting to see something like the following:

Hello World > 2bytes > " b'Hello World' > encryption > #JibberishText# > decryption > b'Hello World' > Hello World

The actual results of this run are:

Hello World > 2bytes > b'Hello World' > encryption > b'\x8eo\xfc`\xeck\xcf\r4\x1fS' > decryption > b'\xc7\x93\x8a\x1dK\xad\xc5\x9d8\x9c\x18'

Also: If i do not comment out the last lines I get the following error:

File "aes.py", line 25, in decrypted_msg = decrypted_bytes_msg.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8e in position 0: invalid start byte

Can you help me understand the way to use the module ?

Legorooj
  • 2,646
  • 2
  • 15
  • 35
ex1led
  • 427
  • 5
  • 21
  • 2
    You got some important stuff wrong here. Your counter never advances, which is a disaster if you're encrypting more than one block. You must reset the cipher to the initial state *prior* to decryption, which means calling `AES.new` again. And you can't create a string out of arbitrary byte sequences with `str.decode`. The simplest way to examine the value of an arbitrary byte sequence is to call the `hex()` method on the bytes object. These are just the bugs I've observed on a quick scan. – President James K. Polk Oct 15 '19 at 13:21

1 Answers1

1

you need to be very careful using the primitives exposed by this module, it's very easy to do the wrong thing and break the crypto system entirely

your code as is doesn't work for me because the counter parameter should be a Crypto.Util.Counter and not function. this presumably works with some versions of the library but it doesn't work for me.

that said, your code is never going to work because you need to "reset" the cipher between encryption and decryption so that the same counter values are used across these operations. the second https://stackoverflow.com/a/45642256/1358308 answer to that question has a much better example of how to use the module

Sam Mason
  • 15,216
  • 1
  • 41
  • 60