Pycrypto AES加密数据有奇怪的符号(python)

时间:2013-11-30 02:07:23

标签: python encryption aes pycrypto undefined-symbol

这里的新手程序员尝试使用pycrypto AES加密数据字符串。仔细分析并在python shell中尝试后,我编写了crypt.py并尝试运行它。当我运行文件时,在shell中运行完美的AES函数开始给出奇怪的符号作为输出。有人可以解释我做错的地方。

这是我的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() 

输出是: crc追加后的最终版:10 | Hi1293356558

填充最终值:10 | Hi1293356558

A0> _y / U

ivp是:95f9a5238701703b8a58933bb48e9015

mqMher2: ]6    75՘+ 2 = PH Ťڕu'5 / Q9a5238701703b5UTfQ


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'

1 个答案:

答案 0 :(得分:-1)

感谢Kyle。这解释并回答了您想要了解的AES pycrypto的所有内容。 http://kyleisom.net/downloads/crypto_intro.pdf