2020年9月8日星期二

CBC and CTR script from book

 CBC


#!/usr/bin/env python

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend

from binascii import hexlify as hexa

from os import urandom

BLOCKLEN = 16

# the blocks() function splits a data string into space-separated blocks def blocks(data):

    split = [hexa(data[i:i+BLOCKLEN]) for i in range(0, len(data), BLOCKLEN)]

return ' '.join(split) k = urandom(16)

print 'k = %s' % hexa(k)

# pick a random IV

iv = urandom(16)

print 'iv = %s' % hexa(iv)

# pick an instance of AES in CBC mode

aes = Cipher(algorithms.AES(k), modes.CBC(iv), backend=default_backend()).encryptor()

p = '\x00'*BLOCKLEN*2

c = aes.update(p) + aes.finalize()

print 'enc(%s) = %s' % (blocks(p), blocks(c)) # now with a different IV and the same key

iv = urandom(16) 

print 'iv = %s' % hexa(iv)

aes = Cipher(algorithms.AES(k), modes.CBC(iv), backend=default_backend()).encryptor()

c = aes.update(p) + aes.finalize()

print 'enc(%s) = %s' % (blocks(p), blocks(c))


CTR mode


#!/usr/bin/env python

from Crypto.Cipher import AES

from Crypto.Util import Counter

from binascii import hexlify as hexa from os import urandom

from struct import unpack

k = urandom(16)

print 'k = %s' % hexa(k)

# pick a starting value for the counter nonce = unpack('<Q', urandom(8))[0]

# instantiate a counter function

ctr = Counter.new(128, initial_value=nonce)

# pick an instance of AES in CTR mode, using ctr as counter

aes = AES.new(k, AES.MODE_CTR, counter=ctr)

# no need for an entire block with CTR

p = '\x00\x01\x02\x03'

# encrypt p

c = aes.encrypt(p)

print 'enc(%s) = %s' % (hexa(p), hexa(c))

# decrypt using the encrypt function

ctr = Counter.new(128, initial_value=nonce) aes = AES.new(k, AES.MODE_CTR, counter=ctr) p = aes.encrypt(c)

print 'enc(%s) = %s' % (hexa(c), hexa(p))

沒有留言:

發佈留言