Securing Secrets on AWS
Link to the meet up: Vancouver Amazon Web Services User Group
Here are the resources from my presentation:
Here are the related sample scripts:
AWS CLI Basic KMS usage:
#!/usr/bin/env bashaws kms list-keys | jq -c ‘.Keys[].KeyArn’ | tr -d ‘"’
aws kms encrypt –key-id fdadc55c-83a8-498a-9efc-d36bb7176506
–plaintext “Hello World” –output text
–query CiphertextBlob | base64 –decode >
./ExampleEncryptedFileaws kms decrypt –ciphertext-blob fileb://.//ExampleEncriptedFile
–output text –query Plaintext | base64 –decode > ExamplePlaintextFile
<p>
<code>AWS CLI Basic KMS with Bash Functions:</code>
</p>
<pre>KEY=fdadc55c-83a8-498a-9efc-d36bb7176506
encrypt (){ aws kms encrypt –key-id $KEY –plaintext “$2” –output text –query CiphertextBlob | base64 –decode > $3 echo “Encrypted: $3” } encrypt $KEY “Hello World2” magic #encrypt $KEY fileb://./test.txt magic decrypt (){ echo “Decrypted: $(aws kms decrypt –ciphertext-blob fileb://$1 –output text –query Plaintext | base64 –decode)” } decrypt magic
<p>
<code>KMS using the Python SDK:</code>
</p>
<pre>#!/usr/bin/env python
import boto3 kms = boto3.client(‘kms’) key = “fdadc55c-83a8-498a-9efc-d36bb7176506” plaintext = ‘Hello, World!’
response_encrypt = kms.encrypt( KeyId=key, Plaintext=plaintext, EncryptionContext={ ‘user’: ‘jfox’ } )
print response_encrypt.get(‘CiphertextBlob’)
response_decrypt = kms.decrypt( CiphertextBlob=response_encrypt.get(‘CiphertextBlob’), EncryptionContext={ ‘user’: ‘jfox’ } ) print response_decrypt.get(‘Plaintext’)
<p>
<code>KMS Envelope Encryption using the Python SDK:</code>
</p>
<pre>#!/usr/bin/env python
import base64 import boto3 from Crypto.Cipher import AES kms = boto3.client(‘kms’) key = “fdadc55c-83a8-498a-9efc-d36bb7176506” plaintext = ‘Hello, World!’
pad = lambda s: s + (32 - len(s) % 32) * ' '
data_key = kms.generate_data_key( KeyId=key, KeySpec=‘AES_256’ ) ciphertext_blob = data_key.get(‘CiphertextBlob’) plaintext_key = data_key.get(‘Plaintext’) crypter = AES.new(plaintext_key) encrypted_data = base64.b64encode(crypter.encrypt(pad(plaintext))) print encrypted_data
decrypted_key = kms.decrypt(CiphertextBlob=ciphertext_blob).get(‘Plaintext’) crypter = AES.new(decrypted_key) decrypted_data = crypter.decrypt(base64.b64decode(encrypted_data)).rstrip() print decrypted_data