"errorMessage": "string argument without an encoding",

"errorMessage": "string argument without an encoding",

我试图在 DynamoDb 中保存加密的密码字符串,但出现此错误。

回复:

{
  "errorMessage": "string argument without an encoding",
  "errorType": "TypeError",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 25, in lambda_handler\n    encrypted_password = encrypt(session, plain_text_password, key_alias)\n",
    "  File \"/var/task/lambda_function.py\", line 11, in encrypt\n    Plaintext=bytes(secret)\n"
  ]
}

这是我正在尝试使用的代码。

import boto3
import base64
from botocore.exceptions import ClientError

def encrypt(session, secret, alias):
    client = session.client('kms')
    ciphertext = client.encrypt(
        KeyId=alias,
        Plaintext=bytes(secret)
    )
    return base64.b64encode(ciphertext["CiphertextBlob"])

def lambda_handler(event, context):

    plain_text_password = event['password']
    username = event['username']
    key_alias = 'alias/ProjectKey'
    table_name = 'Authentication'

    session = boto3.session.Session()
    table = boto3.resource('dynamodb').Table(table_name)

    encrypted_password = encrypt(session, plain_text_password, key_alias)
    print('ENCRYPTED STRING: ' + encrypted_password)

    item = {
        'username':username,
        'password':encrypted_password
    }

    #check if item with the username already exists; if so, update password; else create new item
    entry = table.get_item(TableName=table_name, Key={'username':username})

    # if an entry with that username already exists, then update its corresponding password
    if 'Item' in entry:
        print('Item found. Updating password.')
        print("entry['Item']" + str(entry['Item']))
        response = table.update_item(
            Key={
                'username': username
            },
            UpdateExpression="set password = :p",
            ExpressionAttributeValues={
                ':p': encrypted_password
            },
            ReturnValues="UPDATED_NEW"
        )
    else:
        #if an entry with that username doesn't already exist, then create it
        print('Adding new item to table.')
        table.put_item(Item=item)
        new_entry = table.get_item(TableName=table_name, Key={'username':username})
        if 'Item' in new_entry:
            print('A new item was inserted in the table.')
        else:
            print('Failed to insert new item in table')

    return 'Function succeeded!'

我尝试在 python 2.7 和 python 3 中 运行 但没有成功。 我分别为 Lambda 和 DB 添加了 Lambda 完全访问权限和 dynamodb 完全访问权限角色,对于 KMS,我赋予了相同的访问权限来管理和密钥使用。

您能否提供有关 ciphertext["CiphertextBlob"] 的更多信息(类型,...)?

也许您只需要转换为字节,例如

base64.b64encode(bytes("yourstring", 'utf-8'))

或其他方式

base64.b64encode(ciphertext["CiphertextBlob"].encode('utf-8'))