2017-09-05 82 views
0

我嘗試寫一個代碼,其中我的資料加密,然後我嘗試執行我的代碼我得到一個錯誤:AWS加密類型錯誤:不能Concat的字符串str的字節

import base64 
import boto3 
from Crypto.Cipher import AES 

PAD = lambda s: s + (32 - len(s) % 32) * ' ' 


def get_arn(aws_data): 
    return 'arn:aws:kms:{region}:{account_number}:key/{key_id}'.format(**aws_data) 


def encrypt_data(aws_data, plaintext_message): 
    kms_client = boto3.client(
     'kms', 
     region_name=aws_data['region']) 

    data_key = kms_client.generate_data_key(
     KeyId=aws_data['key_id'], 
     KeySpec='AES_256') 

    cipher_text_blob = data_key.get('CiphertextBlob') 
    plaintext_key = data_key.get('Plaintext') 

    # Note, does not use IV or specify mode... for demo purposes only. 
    cypher = AES.new(plaintext_key, AES.MODE_EAX) 
    encrypted_data = base64.b64encode(cypher.encrypt(PAD(plaintext_message))) 

    # Need to preserve both of these data elements 
    return encrypted_data, cipher_text_blob 



def main(): 
    # Add your account number/region/KMS Key ID here. 
    aws_data = { 
     'region': 'eu-west-1', 
     'account_number': '70117777xxxx', 
     'key_id': 'xxxxxxx-83ac-4b5e-93d4-xxxxxxxx', 
    } 

    # And your super secret message to envelope encrypt... 
    plaintext = b'Hello, World!' 

    # Store encrypted_data & cipher_text_blob in your persistent storage. You will need them both later. 
    encrypted_data, cipher_text_blob = encrypt_data(aws_data, plaintext) 
    print(encrypted_data) 


if __name__ == '__main__': 
    main() 

這是一個錯誤:

PAD = lambda s:s +(32-len(s)%32)*'' TypeError:無法將字節轉換爲字節 可能誰知道問題出在哪裏?請建議

回答

1

你的功能PAD旨在用string投入工作,你(在你的例子b'Hello, World!')與bytes輸入調用它。

PAD('Hello, World!')沒有的領先b)的作品。 一個解決辦法是要墊明文爲string並將其轉換爲bytes之後,例如:

plaintext = PAD('Hello, world!') plaintext_bytes = plaintext.encode('utf-8')

this StackOverflow question如何轉換一個stringbytes

+0

哦,它的工作原理!謝謝,也許你知道我需要使用哪種模式來加密這個字符串? cypher = AES.new(plaintext_key,AES.MODE_EAX)然後我使用這個,我得到:TypeError:只有字節字符串可以傳遞給C代碼,我嘗試使用許多aes.mode但沒有.. :( – Andrej

+0

快樂它的工作原理,在這種情況下,你可以接受我的解決方案;)關於你的第二個問題,你可能會遇到相反的問題:當AES函數需要'bytes'時,你傳遞一個'string'。嘗試用'plaintext_key.encode('utf-8')'調用AES函數來查看這是否解決了這個問題。 – pills

+0

接受!你可以用我的模式給我看看嗎? – Andrej

相關問題