Comment 0 for bug 899818

Revision history for this message
Darsey Litzenberger (dlitz) wrote :

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)