Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách dùng Boto3 lấy khóa bí mật dạng văn bản thuần từ định dạng nhị phân/mã hóa trong AWS Secrets Manager


Đề bài: Sử dụng thư viện boto3 trong Python để lấy khóa bí mật dưới dạng văn bản thuần túy (plain text) từ định dạng nhị phân/mã hóa (binary/encrypted) có trong AWS Secrets Manager.

Cách tiếp cận / Thuật toán

  • Bước 1: Import boto3 và botocore.exceptions để xử lý ngoại lệ.

  • Bước 2: secret_stored_location là tham số bắt buộc. Đây là nơi lưu trữ bí mật.

  • Bước 3: Tạo phiên làm việc AWS bằng boto3. Đảm bảo region_name được cấu hình; nếu không, truyền rõ ràng.

  • Bước 4: Tạo client AWS cho dịch vụ secretsmanager.

  • Bước 5: Gọi get_secret_value với SecretId là secret_stored_location.

  • Bước 6: Kiểm tra xem kết quả là văn bản thuần hay đã mã hóa.

  • Bước 7: Nếu là mã hóa, giải mã giá trị nhị phân bằng base64.b64decode.

  • Bước 8: Trả về tất cả bí mật ở dạng giải mã (plain text) tại vị trí đã cho.

  • Bước 9: Xử lý ngoại lệ chung nếu có lỗi khi truy xuất.

Mã ví dụ

Sử dụng mã sau để lấy bí mật dạng plain text đã giải mã:

import boto3
import base64
from botocore.exceptions import ClientError

def get_decrypted_secret_details(secret_stored_location):
    session = boto3.session.Session()
    s3_client = session.client('secretsmanager')
    try:
        response = s3_client.get_secret_value(SecretId=secret_stored_location)
        if not ('SecretString' in response):
            decoded_secret_values = base64.b64decode(response['SecretBinary'])
            return decoded_secret_values
        return response['SecretString']
    except ClientError as e:
        raise Exception("Lỗi client boto3 trong get_decrypted_secret_details: " + e.__str__())
    except Exception as e:
        raise Exception("Lỗi không mong muốn trong get_decrypted_secret_details: " + e.__str__())

a = get_decrypted_secret_details('/secrets/aws')
print(a)

Kết quả

{"user":"SERVICE_USER","accesskey":"I**************"}