ga('set', 'anonymizeIp', 1);
Categories: CodingPython

[python] pycrypto AES加密 on windows 10

Share

在python上實現AES加解密功能,在環境設定一些除錯跟經驗分享。

環境

OS: Windows 10
python: 3.8

import python lib

pip install pycrypto

若出現安裝錯誤請查看程式碼下方內容

程式碼如下

import base64
from Crypto.Cipher import AES
# 密鑰(key), 密斯偏移量(iv) CBC模式加密

def AES_Encrypt(key, data):
    vi = ‘0102030405060708‘
    pad = lambda s: s + (16 - len(s)%16) * chr(16 - len(s)%16)
    data = pad(data)
    # 字符串補位
    cipher = AES.new(key.encode(‘utf8‘), AES.MODE_CBC, vi.encode(‘utf8‘))
    encryptedbytes = cipher.encrypt(data.encode(‘utf8‘))
    # 加密後得到的是bytes類型的數據
    encodestrs = base64.b64encode(encryptedbytes)
    # 使用Base64進行編碼,返回byte字符串
    enctext = encodestrs.decode(‘utf8‘)
    # 對byte字符串按utf-8進行解碼
    return enctext

def AES_Decrypt(key, data):
    vi = ‘0102030405060708‘
    data = data.encode(‘utf8‘)
    encodebytes = base64.decodebytes(data)
    # 將加密數據轉換位bytes類型數據
    cipher = AES.new(key.encode(‘utf8‘), AES.MODE_CBC, vi.encode(‘utf8‘))
    text_decrypted = cipher.decrypt(encodebytes)
    unpad = lambda s: s[0:-s[-1]]
    text_decrypted = unpad(text_decrypted)
    # 去補位
    text_decrypted = text_decrypted.decode(‘utf8‘)
    return text_decrypted

key = ‘0CoJUm6Qyw8W8jud‘
data = ‘sdadsdsdsfd‘
AES_Encrypt(key, data)
enctext = AES_Encrypt(key, data)
print(enctext)
text_decrypted = AES_Decrypt(key, enctext)
print(text_decrypted)

輸出為:
hBXLrMkpkBpDFsf9xSRGQQ== sdadsdsdsfd

若出現以下錯誤訊息

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

解法:

下載Build Tools for Visual Studio 2015 Update 3個別使用版本

下載visualcppbuildtools_full.exe

安裝完後設定環境變數(設定USER變數)
變數名稱:VCINSTALLDIR
值:C:\ProgramFiles (x86)\Microsoft Visual Studio 14.0\VC

接著使用CMD執行以下指令:
set CL=/FI"%VCINSTALLDIR%\INCLUDE\stdint.h" %CL%

再執行pip install pycrypto

若出現以下錯誤訊息

LINK: fatal error LNK1158: cannot run ‘rc.exe’

解法:


  1. \Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\include\stdint.h
    檔案拷貝到
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.15063.0\ucrt\
    目錄下
    上方版本依照使用者之版本為主。

  2. 修改
    C:\Program Files (x86)\Windows Kits\10\Include\10.0.15063.0\ucrt\inttypes.h中的第13行,將:
    #include <stdint.h>
    修改為
    #include "<stdint.h>"

接著,將
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
下的 rc.exe 和 rcdll.dll 複製到
C:\Program Files (x86)\Microsoft\Visual_Studio\v14.0\VC\bin

最後再次執行pip install pycrypto
錯誤即可解決。

Jys

Published by
Jys

Recent Posts

[python] Flask Create RESTful API

This article gi... Read More

2 年 前發表

[Javascript] 新增/刪除JSON中key值

在web訊息交換常會需要對JS... Read More

2 年 前發表

[JAVA] SQL Server Connection

本文介紹JAVA連線SQL s... Read More

3 年 前發表