python3實現CryptoJS AES加密演算法

2021-10-12 20:49:10 字數 1826 閱讀 7136

from crypto.cipher import aes

from binascii import b2a_hex, a2b_hex

import base64

class

aescrypt

:def

__init__

(self, __key)

: self.key = __key.encode(

'utf8'

) self.mode = aes.mode_ecb # 模式可以更改為mode_cbc需要新增vi

# 生成加密器,引數:密匙,模式

self.cryptor = aes.new(self.key, self.mode)

@staticmethod

defadd_to_16

(text)

: pad =16-

len(text.encode(

'utf-8'))

%16text = text + pad *

chr(pad)

return text.encode(

'utf-8'

)def

encrypt

(self, text, base=16)

:""" 加密方法

:param text: 需要加密的文字

:param base: 需要加密的型別

:return:加密完的字串

"""# 預處理,填充明文為16的倍數

text = self.add_to_16(text)

# 加密,輸出bytes型別

cipher_text = self.cryptor.encrypt(text)

if base ==16:

# 返回16進製制密文

return b2a_hex(cipher_text)

.decode(

'utf-8'

)elif base ==64:

# 返回base64密文

return base64.b64encode(cipher_text)

.decode(

'utf-8'

)def

decrypt

(self, ciphertext, base=16)

:if base ==16:

# 解密16進製制密文

text = a2b_hex(ciphertext)

elif base ==64:

# 解密base64密文

text = base64.b64decode(ciphertext)

# base64解碼

else

:raise exception(

'不支援的編碼'

) utf8_text = self.cryptor.decrypt(text)

.decode(

'utf8'

)return utf8_text[0:

-ord

(utf8_text[-1

])]if __name__ ==

'__main__'

: key =

'd5fdec7c7746261f'

txt =

'123456'

ase = aescrypt(key)

print

(ase.encrypt(txt)

)print

(ase.decrypt(

'6e670907d658b6d35167cd2b41f3a565'

))

python3 安裝Crypto 出現的問題

先導入所需要的包 pip3 install crypto 再安裝pycrypto pip3 install pycrypto fromcrypto.cipherimportaes 就成功了 python3安裝crypto出錯,及解決方法 首先我用的python3.5的版本 問題的由來,我想通過pyt...

Python3 安裝 Crypto 三方庫

安裝 pip install pycryptodome安裝完後導包 from crypto.cipher import aes發現竟然有錯 importerror no module named crypto 最後才發現,我需要在 python 環境中改下包的名字,cd users zhangyi ...

Python3 實現選擇排序

選擇排序 selection sort 原理很簡單,就是依次在未排序資料段中選擇出乙個最小的數,然後將其排列在已排序資料段末端,直到整個資料段排序完成演算法結束。程式如下,第乙個迴圈依次縮小未排序資料段的長度,並且每次將最小值暫定為未排序中第一位索引。第二個迴圈依次將該最小值與未排序資料段作比較,選...