How to Test AWS KMS Access: A Step-by-Step Guide for Developers

Are you struggling to verify if your AWS credentials have the right permissions to use your Customer Managed Key (CMK) in KMS? While AWS Access Analyzer is an excellent tool for this purpose, it’s not always available. In this guide, we’ll walk you through a practical alternative using a Python script to test your KMS access.

Prerequisites

Before we begin, ensure you have:

  1. Python 3 installed (python3 --version)
  2. AWS credentials (Access Key and Secret Access Key)
  3. Basic knowledge of AWS KMS and Python

Step 1: Setting Up Your Environment

First, let’s set up our development environment:

# Install Python (if not already installed)
brew install python

# Create and activate a virtual environment
python3 -m venv venv
source venv/bin/activate

# Install required packages
pip install boto3 cryptography

Step 2: Creating the KMS Test Script

Create a new file named kms_test.py and add the following code:

import boto3
import os
from cryptography.fernet import Fernet

def test_kms_encryption():
    # AWS credentials
    aws_access_key_id = 'YOUR_ACCESS_KEY_HERE'
    aws_secret_access_key = 'YOUR_SECRET_KEY_HERE'
    aws_region = 'YOUR_AWS_REGION_HERE'
 
    # Initialize KMS client with credentials
    session = boto3.Session(
        aws_access_key_id=aws_access_key_id,
        aws_secret_access_key=aws_secret_access_key,
        region_name=aws_region
    )
    kms = session.client('kms')

    # Generate a test API key
    test_api_key = Fernet.generate_key().decode()

    # Encrypt the test API key using KMS
    try:
        response = kms.encrypt(
            KeyId='alias/your-new-cmk-alias',  # Replace with your KMS ARN
            Plaintext=test_api_key.encode()
        )
        encrypted_key = response['CiphertextBlob']
    except Exception as e:
        print(f"Encryption failed: {str(e)}")
        return False

    # Decrypt the API key
    try:
        response = kms.decrypt(
            CiphertextBlob=encrypted_key
        )
        decrypted_key = response['Plaintext'].decode()
    except Exception as e:
        print(f"Decryption failed: {str(e)}")
        return False

    # Compare original and decrypted keys
    if test_api_key == decrypted_key:
        print("Test passed: Encryption and decryption successful")
        return True
    else:
        print("Test failed: Decrypted key does not match original")
        return False

# Run the test
if __name__ == "__main__":
    test_kms_encryption()

Important: Replace 'YOUR_ACCESS_KEY_HERE', 'YOUR_SECRET_KEY_HERE', 'YOUR_AWS_REGION_HERE', and 'alias/your-new-cmk-alias' with your actual AWS credentials and KMS key details.

Step 3: Running the Test

Execute the script using:

python kms_test.py

You’ll see one of two outcomes:

  1. “Test passed: Encryption and decryption successful” – Your KMS access is working correctly.
  2. An error message – Indicating an issue with your KMS access or credentials.

Conclusion

This simple Python script provides a quick and effective way to test your AWS KMS access without relying on Access Analyzer. By encrypting and decrypting a test key, you can verify your application’s permissions and ensure smooth integration with AWS KMS.

Remember to handle your AWS credentials securely and never commit them to version control systems.