1 Python27 安裝crypto
Windows安裝
在Windows上安裝的時候直接 pip install pycrypto會報錯,參考:http://blog.csdn.net/teloy1989/article/details/72862108
2.安裝 Microsoft Visual C++ 9.0
由於直接安裝安裝Crypto模塊 會報錯如下:因此需要先安裝Microsoft Visual C++ 9.0
2.1 進入下載網址:https://www.microsoft.com/en-us/download/confirmation.aspx?id=44266,直接下載后點擊安裝
下載的軟件是VCForPython27.msi,安裝好后,pip install pycrypto
2 解決Python27的編碼錯誤
1 設置代碼的格式
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
2 解密的時候遇到問題
Python2切片無法知己獲取字節的值,獲取的是hex 16進制,查詢16進制轉換10進制的時候,用 binascii.a2b_hex報錯
下面自己先獲取到最后添加的值,把最后的最編碼成utf8,再編碼成hex,結果就是hex的字符串,自己寫的hexstring2int函數,直接把相應的值轉換成數字
a_end_bytes = result[-1] # 獲取到的最后一個數值
temp_vlue = a_end_bytes.encode('utf-8') # 加密的時候 把字節解碼成字符串 在這里重新編碼成utf-8
num_value = temp_vlue.encode('hex') # 將獲取到的字符串轉換成數字
res = hexstring2int(num_value) # 將hex轉換成數字
data = result[0:-res] # 獲取真實的內容
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from Crypto.Cipher import AES
def hexstring2int(code):
if code == '01':
return 1
elif code == '02':
return 2
elif code == '03':
return 3
elif code == '04':
return 4
elif code == '05':
return 5
elif code == '06':
return 6
elif code == '07':
return 7
elif code == '08':
return 8
elif code == '09':
return 9
elif code == '0a':
return 10
elif code == '0b':
return 11
elif code == '0c':
return 12
elif code == '0d':
return 13
elif code == '0e':
return 14
elif code == '0f':
return 15
elif code == '10':
return 16
def encrypt(message):
key = b'jlaksdflj77asdfh' # 16個字節或16字節的倍數
cipher = AES.new(key, AES.MODE_CBC, key)
byte_data = bytearray(message, encoding='utf8') # 想要動態修改字節,用bytearray 相當於把字節轉換成一個數組
v1 = len(byte_data) # 這是要加密的數據的長度 21
v2 = v1 % 16 # 取余 5
if v2 == 0:
v3 = 16
else:
v3 = 16 - v2 # 這是要補足的數 11 : 21+11=32 是16的倍數
for i in range(v3):
byte_data.append(v3)
final_data = byte_data.decode('utf-8') # 把字節解碼成字符串
msg = cipher.encrypt(final_data) # 進行加密 final_data必須是16個字節或16字節的倍數
return msg
# ############## 解密 ##############
def decrypt(msg):
key = b'jlaksdflj77asdfh' # 需要同樣的key 6個字節或16字節的倍數
cipher = AES.new(key, AES.MODE_CBC, key)
result = cipher.decrypt(msg) # 對字節進行解密
a_end_bytes = result[-1] # 獲取到的最后一個數值
temp_vlue = a_end_bytes.encode('utf-8') # 加密的時候 把字節解碼成字符串 在這里重新編碼成utf-8
num_value = temp_vlue.encode('hex') # 將獲取到的字符串轉換成數字
res = hexstring2int(num_value) # 將hex轉換成數字
data = result[0:-res] # 獲取真實的內容
return data
if __name__ == '__main__':
msg = encrypt(u"哈哈哈")
data = decrypt(msg)
print data
