A novice programmer here trying to encrypt a data string using pycrypto AES. After careful analysis and trying it out in python shell, I have coded crypt.py and tried running it. The AES function which was running perfectly in the shell started giving out strange symbols as output when i run the file. Can someone shed some light on where I am doing wrong.
Here is my crypt.py:
#!/usr/bin/env python
from Crypto.Cipher import AES
from Crypto import Random
import os
import md5
import sys
import binascii
import base64
password = "fault_tolerant_system"
md5obj = md5.new()
md5obj.update(password)
key = md5obj.digest()
def pad(data, width):
needed = width - ((len(data) + 1) % width)
return data + ('\x00' * needed) + chr(needed + 1)
def unpad(data):
padding = ord(data[-1])
return data[:-padding]
def main() :
val = "Hi I am ked"
crcval = binascii.crc32(val) & 0xffffffff
lencrc = len(str(crcval))
finalval = str(lencrc) + "|" + val + str(crcval)
print 'finalval after crc appending: ', finalval
padded_finalval = pad(finalval, 16)
print "padded final val : ", padded_finalval
#encrypt using AES
print Random.new().read(16)
ivp = binascii.hexlify(Random.new().read(16))
aes_encryptor = AES.new(key, AES.MODE_CBC, ivp[:16])
cipher2 = aes_encryptor.encrypt(padded_finalval)
print "ivp is:", ivp
print "cipher2: ", cipher2
cipher = ivp[:16] + aes_encryptor.encrypt(padded_finalval)
print "cipher: ", (cipher)
print "\n\n******"
res_enc_iv_aes = cipher
ivg = res_enc_iv_aes[:16]
print ivg
aes_decryptor = AES.new(key, AES.MODE_CBC, ivg)
print binascii.hexlify(aes_decryptor.decrypt(res_enc_iv_aes[16:]))
resvalue = unpad(aes_decryptor.decrypt(res_enc_iv_aes[16:]))
print "\ndecrpted: ", resvalue
crclen = int(resvalue.split("|", 1)[0])
print "crclen: ", crclen
crc_cksum = resvalue[-crclen:]
print crc_cksum
recv_data = finalval[len(str(crclen))+1 : -crclen]
print "recv_data: ", recv_data
#compute checksum of recv_data
crc_recv_data = binascii.crc32(recv_data) & 0xffffffff
print crc_recv_data
if str(crc_recv_data) == crc_cksum:
#no error in data
print "recv_data: ", recv_data
else:
print "error :("
print "recdata:", recv_data
if __name__ == "__main__":
main()
And the output is: finalval after crc appending: 10|Hi1293356558
padded final val : 10|Hi1293356558
A0>�̔�ˈ�_Y/�u
ivp is: 95f9a5238701703b8a58933bb48e9015
mqMher2: ����]6� �75���+�2=��P�H�� T��ڕu'5/�Q�9a5238701703b5�U���T���fQ�
95f9a5238701703b
edd08277e52fc138369bb557e24d88d000000000000000000000000000000011
decrpted: C���)�{��I3,p
Traceback (most recent call last):
File "cry1.py.py", line 70, in <module>
main()
File "cry1.py.py", line 53, in main
crclen = int(resvalue.split("|", 1)[0])
ValueError: invalid literal for int() with base 10: 'C\xe0\xe9\x1a'