2016-02-27 62 views
0

我試圖做一些嘗試在加密和使用PyCrypto.AES解密,當我嘗試解密它時,「STR」不支持緩衝界面給我TypeError: 'str' does not support the buffer interface類型錯誤:使用PyCrypto.AES

我找到了一些解決方案,其中我必須編碼或使用字符串,但我不知道如何使用它。

AESModule.py

from Crypto.Cipher import AES 
#base64 is used for encoding. dont confuse encoding with encryption# 
#encryption is used for disguising data 
#encoding is used for putting data in a specific format 
import base64 
# os is for urandom, which is an accepted producer of randomness that 
# is suitable for cryptology. 
import os 

def encryption(privateInfo,secret,BLOCK_SIZE): 
    #32 bytes = 256 bits 
    #16 = 128 bits 
    # the block size for cipher obj, can be 16 24 or 32. 16 matches 128 bit. 
    # the character used for padding 
    # used to ensure that your value is always a multiple of BLOCK_SIZE 
    PADDING = '{' 
    # function to pad the functions. Lambda 
    # is used for abstraction of functions. 
    # basically, its a function, and you define it, followed by the param 
    # followed by a colon, 
    # ex = lambda x: x+5 
    pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING 
    # encrypt with AES, encode with base64 
    EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) 
    # generate a randomized secret key with urandom 
    #secret = os.urandom(BLOCK_SIZE) 
    print('Encryption key:',secret) 
    # creates the cipher obj using the key 
    cipher = AES.new(secret) 
    # encodes you private info! 
    encoded = EncodeAES(cipher, privateInfo) 
    print('Encrypted string:', encoded) 
    return(encoded) 

def decryption(encryptedString,secret): 
    PADDING = '{' 
    DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) 
    #Key is FROM the printout of 'secret' in encryption 
    #below is the encryption. 
    encryption = encryptedString 
    cipher = AES.new(secret) 
    decoded = DecodeAES(cipher, encryption) 
    print(decoded) 

test.py

import AESModule 
import base64 
import os 

BLOCK_SIZE = 16 
key = os.urandom(BLOCK_SIZE) 
c = AESRun2.encryption('password',key,BLOCK_SIZE) 
AESRun2.decryption(c,key) 

回答

2

字符串(str)是文本。加密並不在文字處理,它涉及以字節爲單位(bytes)。

在實踐中插入.encode.decode調用必要在兩者之間轉換。我推薦使用UTF-8編碼。

在你的情況,因爲您已經編碼以及密文作爲鹼-64這是另外一個字節/文本轉換解碼,只需要進行編碼和解碼的明文。路過的時候它變成了加密的功能與.encode("utf-8")編碼您的字符串,並得到它的解密函數時最終結果與.decode("utf-8")解碼。

如果您正在閱讀示例或教程,請確保它們適用於Python 3.在Python 2中str是一個字節字符串,將它用於文本和字節是很常見的,這非常容易混淆。在Python 3中,他們修復了它。

+0

什麼.encode和 '.decode' 到底是什麼? – user2415415

+0

@userrandomnumbers:已編輯。 –