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)
# 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)
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 Counter. new(64, prefix=nonce))
e = AES.new("k"*16, AES.MODE_CTR, counter=
ciphertext = e.encrypt("hello world!")
# Decrypt using AES-256 in CTR mode Counter. new(64, prefix=nonce)) ciphertext)
d = AES.new("k"*16, AES.MODE_CTR, counter=
plaintext = d.decrypt(
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): to_long( nonce) << 64) bytes(self. c)
def __init__(self, nonce):
self.c = (bytes_
def __call__(self):
self.c += 1
return long_to_
# Pick a random 64-bit nonce
nonce = get_random_bytes(8)
# Encrypt using AES-256 in CTR mode MyCounter( nonce))
e = AES.new("k"*32, AES.MODE_CTR, counter=
ciphertext = e.encrypt("hello world!")
# Decrypt using AES-256 in CTR mode MyCounter( nonce)) ciphertext)
d = AES.new("k"*32, AES.MODE_CTR, counter=
plaintext = d.decrypt(