aboutsummaryrefslogtreecommitdiffstats
path: root/crypto.py
blob: c5d28d2d0ed4017292f93b9e7aafd7f09ddf6724 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from Crypto.Cipher import AES
import os

def encrypt(msg,key,block_size):
    pad = block_size - len(msg) % block_size
    data = msg + pad * chr(pad)
    iv = os.urandom(block_size)
    cipheredtext = iv + AES.new(key, AES.MODE_CBC, iv).encrypt(data)
    return cipheredtext

def decrypt(cipheredtext,key,block_size):
    iv = cipheredtext[:block_size]
    msg = AES.new(key, AES.MODE_CBC, iv).decrypt(cipheredtext[block_size:])
    #remove the padding
    pad = ord(msg[-1])
    msg = msg[:-pad] 
    return msg
    
if __name__ == '__main__' :
    block_size = 16
    key_size = 32
    key = os.urandom(key_size)
 
    msg1 = 'Guillaume is a genius!'
    msg2 = encrypt(msg1,key,block_size)
    msg3 = decrypt(msg2,key,block_size)
    print "original message: " + msg1
    print "encrypted message: " + msg2.encode('hex')
    print 'verification: ' + msg3