MODE_CTR and Crypto.Util.Counter should be documented

Bug #899818 reported by Darsey Litzenberger
16
This bug affects 3 people
Affects Status Importance Assigned to Milestone
Python-Crypto
Confirmed
Undecided
Unassigned

Bug Description

CTR mode is probably the best unauthenticated block cipher mode of operation out there, and the PyCrypto documentation for it sucks.

Here's some sample code that uses the fast Crypto.Util.Counter implementation:

    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    from Crypto.Util import Counter

    # Pick a random 64-bit nonce
    nonce = get_random_bytes(8)

    # Encrypt using AES-256 in CTR mode
    e = AES.new("k"*16, AES.MODE_CTR, counter=Counter.new(64, prefix=nonce))
    ciphertext = e.encrypt("hello world!")

    # Decrypt using AES-256 in CTR mode
    d = AES.new("k"*16, AES.MODE_CTR, counter=Counter.new(64, prefix=nonce))
    plaintext = d.decrypt(ciphertext)

Here's some functionally equivalent code that uses plain Python, rather than the faster Crypto.Util.Counter implementation:

    from Crypto.Cipher import AES
    from Crypto.Random import get_random_bytes
    from Crypto.Util.number import bytes_to_long, long_to_bytes

    class MyCounter(object):
        def __init__(self, nonce):
            self.c = (bytes_to_long(nonce) << 64)
        def __call__(self):
            self.c += 1
            return long_to_bytes(self.c)

    # Pick a random 64-bit nonce
    nonce = get_random_bytes(8)

    # Encrypt using AES-256 in CTR mode
    e = AES.new("k"*32, AES.MODE_CTR, counter=MyCounter(nonce))
    ciphertext = e.encrypt("hello world!")

    # Decrypt using AES-256 in CTR mode
    d = AES.new("k"*32, AES.MODE_CTR, counter=MyCounter(nonce))
    plaintext = d.decrypt(ciphertext)

Changed in pycrypto:
status: New → Confirmed
minidou (psikobare)
description: updated
Revision history for this message
Andrew Cooke (ato2gx513oupn-andrew-n1by9anq91ai4) wrote :

isn't it better to use the full block size as a random offset and then wraparound? that way you distribute even duplicate messages across the entire space available.

Revision history for this message
Andrew Cooke (ato2gx513oupn-andrew-n1by9anq91ai4) wrote :

sorry; please ignore comment above - it's obviously equivalent for any lossless combination of nonce and counter (and random offset is equivalent to adding nonce and counter, instead of appending)

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.