14.12.2020

Generate Kms Key Using Boto3

Generate Kms Key Using Boto3 Rating: 7,8/10 2910 reviews
  1. Generate Kms Key Using Boto3 Mac
  2. Generate Kms Key Using Boto3 Free

Generate a Data Key (DK). DK can be a key of any length. When you generate a DK, KMS will provide you with both the plain-text key, and the encrypted key, that was encrypted using a specific CMK (specified during the request). By allowing you to control who has access to use the CMKs, list all the CMKs in KMS under an account, etc. You can use the plaintext key to encrypt your data outside of AWS KMS and store the encrypted data key with the encrypted data. GenerateDataKey returns a unique data key for each request. The bytes in the key are not related to the caller or CMK that is used to encrypt the data key.

kmsencrypt.py
#!/usr/bin/env python
''
kmsencrypt.py
AWS kms + python Cryptography library file encrypt and decrypt
This will perform a file encryption and decryption using AWS KMS for generating a data key
rather than using the Fernet generate_key function.
Assumes that AWS access key, secret or token have been setup outside using credentials file or envvars
!! WARNING - I am not a security expert so use at your own risk !!
''
importsys
importbase64
importboto3
fromcryptography.fernetimportFernet
KEY_ID='alias/my_key'# <- place you kms keyid or alias here
defmain():
# get a data key from kms
kms_client=boto3.client('kms')
data_key_dict=kms_client.generate_data_key(
KeyId=KEY_ID, KeySpec='AES_256')
# get the components from kms response
encrypted_key=base64.b64encode(data_key_dict['CiphertextBlob'])
master_key_id=data_key_dict['KeyId']
plain_key=base64.b64encode(data_key_dict['Plaintext'])
# encrypt file with data key using cryptography.fernet library
withopen('./data.txt', mode='rb') asdata_fh:
cipher=Fernet(plain_key)
encrypted_data_content=cipher.encrypt(data_fh.read())
# remove sensitive variables
delplain_key, cipher, data_key_dict
# write content to file
withopen('./data.txt.enc', mode='wb') asencdata_fh:
encdata_fh.write(encrypted_data_content)
print('Encryped file...')
print('enckey={}nmasterkey={}'.format(encrypted_key, master_key_id))
#---------------------------------------------------------------
# OK, lets decrypt the file. You only have the encrypted key to work with
#---------------------------------------------------------------
# decrypt the data key using aws kms
data_key_dict=kms_client.decrypt(CiphertextBlob=base64.b64decode(encrypted_key))
plain_key=base64.b64encode(data_key_dict['Plaintext'])
# decrypt the file using plan key and fernet
cipher=Fernet(plain_key)
withopen('./data.txt.enc', mode='rb') asencdata_fh:
data=cipher.decrypt(encdata_fh.read())
# remove the key variables
delplain_key, cipher, data_key_dict
print('nDecrypted file...')
print('The content is as follows:n{}'.format(data.decode()))
if__name__'__main__':
sys.exit(int(main() or0))
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment
Permalink

Join GitHub today

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Sign up
Branch:master

Generate Kms Key Using Boto3 Mac

Find file Copy path
Fetching contributors…
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License'). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the 'license' file accompanying this file. This file is
# distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
''Example showing use of AWS KMS CMP with EncryptedTable.''
importboto3
fromboto3.dynamodb.typesimportBinary
fromdynamodb_encryption_sdk.encrypted.tableimportEncryptedTable
fromdynamodb_encryption_sdk.identifiersimportCryptoAction
fromdynamodb_encryption_sdk.material_providers.aws_kmsimportAwsKmsCryptographicMaterialsProvider
fromdynamodb_encryption_sdk.structuresimportAttributeActions
defencrypt_item(table_name, aws_cmk_id):
''Demonstrate use of EncryptedTable to transparently encrypt an item.''
index_key= {'partition_attribute': 'is this', 'sort_attribute': 55}
plaintext_item= {
'example': 'data',
'some numbers': 99,
'and some binary': Binary(b'x00x01x02'),
'leave me': 'alone', # We want to ignore this attribute
}
# Collect all of the attributes that will be encrypted (used later).
encrypted_attributes=set(plaintext_item.keys())
encrypted_attributes.remove('leave me')
# Collect all of the attributes that will not be encrypted (used later).
unencrypted_attributes=set(index_key.keys())
unencrypted_attributes.add('leave me')
# Add the index pairs to the item.
plaintext_item.update(index_key)
# Create a normal table resource.
table=boto3.resource('dynamodb').Table(table_name) # generated code confuse pylint: disable=no-member
# Create a crypto materials provider using the specified AWS KMS key.
aws_kms_cmp=AwsKmsCryptographicMaterialsProvider(key_id=aws_cmk_id)
# Create attribute actions that tells the encrypted table to encrypt all attributes except one.
actions=AttributeActions(
default_action=CryptoAction.ENCRYPT_AND_SIGN, attribute_actions={'leave me': CryptoAction.DO_NOTHING}
)
# Use these objects to create an encrypted table resource.
encrypted_table=EncryptedTable(table=table, materials_provider=aws_kms_cmp, attribute_actions=actions)
# Put the item to the table, using the encrypted table resource to transparently encrypt it.
encrypted_table.put_item(Item=plaintext_item)
# Get the encrypted item using the standard table resource.
encrypted_item=table.get_item(Key=index_key)['Item']
# Get the item using the encrypted table resource, transparently decyrpting it.
decrypted_item=encrypted_table.get_item(Key=index_key)['Item']
# Verify that all of the attributes are different in the encrypted item
fornameinencrypted_attributes:
assertencrypted_item[name] !=plaintext_item[name]
assertdecrypted_item[name] plaintext_item[name]
# Verify that all of the attributes that should not be encrypted were not.
fornameinunencrypted_attributes:
assertdecrypted_item[name] encrypted_item[name] plaintext_item[name]
# Clean up the item
encrypted_table.delete_item(Key=index_key)

Generate Kms Key Using Boto3 Free

  • Copy lines
  • Copy permalink