0

I am creating a Python function to perform counter mode encryption using the PyCrypto module. I am aware of the builtin, but want to implement it myself.

I'm trying Test Vector #1 from RFC 3686, and have the correct Counter Block and the correct Key in ASCII form. But when I encrypt the Counter Block using the Key, I don't get the expected Key Stream.

The relevant parts of my code:

cipher = AES.new(key)
ctr_block = iv + nonce + ctr
key_stream = base64.b64decode(cipher.encrypt(ctr_block))

I can provide more code if needed, but I'm not sure how because ctr_block and key have many question mark characters when I print them.

Why am I not getting the expected answer? It seems like everything should go right. Perhaps I made some mistake with the encoding of the string.

Edit

Self-contained code:

from Crypto.Cipher import AES
import base64

def hex_to_str(hex_str):
    return str(bytearray([int(n, 16) for n in hex_str.split()]))

key = hex_to_str("AE 68 52 F8 12 10 67 CC 4B F7 A5 76 55 77 F3 9E")
iv = hex_to_str("00 00 00 00 00 00 00 00")
nonce = hex_to_str("00 00 00 30")
ctr = hex_to_str("00 00 00 01")

cipher = AES.new(key)
ctr_block = iv + nonce + ctr
key_stream = base64.b64decode(cipher.encrypt(ctr_block))

print "".join([hex(ord(char)) for char in key_stream])
# 0xd90xda0x72
Community
  • 1
  • 1
LonelyWebCrawler
  • 2,866
  • 4
  • 37
  • 57

2 Answers2

1

First, use byte strings:

In [14]: keystring = "AE 68 52 F8 12 10 67 CC 4B F7 A5 76 55 77 F3 9E"

In [15]: keystring.replace(' ', '').decode('hex')
Out[15]: '\xaehR\xf8\x12\x10g\xccK\xf7\xa5vUw\xf3\x9e'

Second, you shouldn't use base64.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
1

First, the correct CTR block order is nonce + iv + ctr. Second, that base64.b64decode call is wrong: cipher.encrypt produces a decoded string. After these two fixes your code prints 0xb70x600x330x280xdb0xc20x930x1b0x410xe0x160xc80x60x7e0x620xdf which seems to be a correct key stream.

wRAR
  • 25,009
  • 4
  • 84
  • 97
  • Yes! Thank you. I got the incorrect `b64encode` part from a [blog post](http://www.codekoala.com/blog/2009/aes-encryption-python-using-pycrypto/) which I misinterpreted. – LonelyWebCrawler Apr 01 '13 at 01:17