본문 바로가기

퍼블릭 클라우드

[aws] AWS Key Management Service (KMS)를 사용하여 Python에서 테스트하는 방법

728x90

AWS Key Management Service (KMS)를 사용하여 Python에서 테스트하는 방법

테스트 환경

$ lsb_release -d
Description:    Ubuntu 22.04.2 LTS

python 설치

sudo apt install -y python3 python3-pip
$ python3 --version
Python 3.10.6

$ pip --version
pip 23.1.2 from /usr/local/lib/python3.10/dist-packages/pip (python 3.10)

1. AWS CLI 구성

AWS CLI를 사용하여 AWS 계정에 액세스할 수 있는지 확인합니다. AWS CLI를 설치하고, AWS 계정 자격 증명을 구성합니다. 자세한 내용은 AWS CLI 설치 및 구성 가이드를 참조하십시오.

AWS CLI 설치 및 구성 가이드(aws cli를 설치하는 방법) : https://sangchul.kr/657

2. Boto3 설치

Boto3는 AWS SDK for Python으로, AWS 서비스와 상호 작용하기 위한 Python 라이브러리입니다. Boto3를 설치합니다. 터미널 또는 명령 프롬프트에서 다음 명령을 실행합니다.

pip install boto3

3. Python 스크립트 작성

다음과 같이 Python 스크립트를 작성하여 KMS를 사용하여 데이터를 암호화하고 복호화할 수 있습니다. 스크립트에는 AWS 계정의 액세스 키 및 시크릿 액세스 키가 필요합니다.

import boto3
import base64

# AWS 액세스 키 및 시크릿 액세스 키 구성
aws_access_key_id = 'YOUR_AWS_ACCESS_KEY_ID'
aws_secret_access_key = 'YOUR_AWS_SECRET_ACCESS_KEY'
region_name = 'YOUR_AWS_REGION'  # 예: 'us-west-2'

# KMS 클라이언트 생성
client = boto3.client('kms', aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name)

# 암호화할 데이터
plaintext = b'This is a test message.'

# KMS를 사용하여 데이터 암호화
response = client.encrypt(
    KeyId='YOUR_KMS_KEY_ARN',  # KMS 키의 ARN
    Plaintext=plaintext
)

# 암호화된 데이터와 메타데이터 추출
ciphertext_blob = response['CiphertextBlob']
encryption_context = response['EncryptionContext']

print('암호화된 데이터:')
print(base64.b64encode(ciphertext_blob))

# KMS를 사용하여 데이터 복호화
response = client.decrypt(
    CiphertextBlob=ciphertext_blob,
    EncryptionContext=encryption_context
)

# 복호화된 데이터 추출
decrypted_plaintext = response['Plaintext']

print('복호화된 데이터:')
print(decrypted_plaintext)

위의 스크립트에서 필요한 값들을 적절하게 수정해야 합니다.

  • YOUR_AWS_ACCESS_KEY_ID: AWS 액세스 키 ID로 대체합니다.
  • YOUR_AWS_SECRET_ACCESS_KEY: AWS 시크릿 액세스 키로 대체합니다.
  • YOUR_AWS_REGION: AWS 리전으로 대체합니다. 예를 들어, 'us-west-2'는 미국 서부 (오레곤)을 나타냅니다.
  • YOUR_KMS_KEY_ARN: 사용할 KMS 키의 ARN으로 대체합니다. 예를 들어, 'arn:aws:kms:us-west-2:123456789012:key
728x90

고객 관리형 키(cmk) 테스트

  • Python 라이브러리 설치
pip install boto3 pycryptodome
  • cmk.python 파일 작성
vim cmk.python
import boto3
import base64
from Crypto.Cipher import AES

BLOCK_SIZE = 32
PADDING = b'|'  # Make PADDING a bytes object instead of a string

key_arn = 'arn:aws:kms:ap-northeast-2:XXXXX:key/yyyyy'
message = 'This is a test for KMS.'

client = boto3.client('kms')

data_key = client.generate_data_key(
    KeyId=key_arn,
    KeySpec='AES_256'
)

pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

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

###### Encrypted data ########
encryptor = AES.new(plaintext_key, AES.MODE_ECB)
encrypted_data = base64.b64encode(encryptor.encrypt(pad(message.encode('utf-8'))))

print("########## Encrypted Data ##############")
print(encrypted_data)

###### Decrypted data ########
decrypted_key = client.decrypt(CiphertextBlob=encrypted_key).get('Plaintext')
decryptor = AES.new(decrypted_key, AES.MODE_ECB)

decrypted_str = decryptor.decrypt(base64.b64decode(encrypted_data)).decode('utf-8')

print("########## Decrypted Data ##############")
print(decrypted_str.rstrip(PADDING.decode('utf-8')))
  • cmk.python 실행
$ python3 cmk.python
########## Encrypted Data ##############
b'lOlydokU8ulervDSraak9Bfk7nD1e5zdrDYD+cyAadA='
########## Decrypted Data ##############
This is a test for KMS.

 

참고URL

- AWS KMS 어렵지 않아요 : https://bluese05.tistory.com/71

 

728x90