| 19 | |
| 20 | # snippet-start:[python.example_code.kms.KeyEncrypt.decl] |
| 21 | class KeyEncrypt: |
| 22 | def __init__(self, kms_client): |
| 23 | self.kms_client = kms_client |
| 24 | |
| 25 | @classmethod |
| 26 | def from_client(cls) -> "KeyEncrypt": |
| 27 | """ |
| 28 | Creates a KeyEncrypt instance with a default KMS client. |
| 29 | |
| 30 | :return: An instance of KeyEncrypt initialized with the default KMS client. |
| 31 | """ |
| 32 | kms_client = boto3.client("kms") |
| 33 | return cls(kms_client) |
| 34 | |
| 35 | # snippet-end:[python.example_code.kms.KeyEncrypt.decl] |
| 36 | |
| 37 | # snippet-start:[python.example_code.kms.Encrypt] |
| 38 | def encrypt(self, key_id: str, text: str) -> bytes: |
| 39 | """ |
| 40 | Encrypts text by using the specified key. |
| 41 | |
| 42 | :param key_id: The ARN or ID of the key to use for encryption. |
| 43 | :param text: The text to encrypt. |
| 44 | :return: The encrypted version of the text. |
| 45 | """ |
| 46 | try: |
| 47 | response = self.kms_client.encrypt(KeyId=key_id, Plaintext=text.encode()) |
| 48 | print( |
| 49 | f"The string was encrypted with algorithm {response['EncryptionAlgorithm']}" |
| 50 | ) |
| 51 | return response["CiphertextBlob"] |
| 52 | except ClientError as err: |
| 53 | if err.response["Error"]["Code"] == "DisabledException": |
| 54 | logger.error( |
| 55 | "Could not encrypt because the key %s is disabled.", key_id |
| 56 | ) |
| 57 | else: |
| 58 | logger.error( |
| 59 | "Couldn't encrypt text. Here's why: %s", |
| 60 | err.response["Error"]["Message"], |
| 61 | ) |
| 62 | raise |
| 63 | |
| 64 | # snippet-end:[python.example_code.kms.Encrypt] |
| 65 | |
| 66 | # snippet-start:[python.example_code.kms.Decrypt] |
| 67 | def decrypt(self, key_id: str, cipher_text: bytes) -> str: |
| 68 | """ |
| 69 | Decrypts text previously encrypted with a key. |
| 70 | |
| 71 | :param key_id: The ARN or ID of the key used to decrypt the data. |
| 72 | :param cipher_text: The encrypted text to decrypt. |
| 73 | :return: The decrypted text. |
| 74 | """ |
| 75 | try: |
| 76 | return self.kms_client.decrypt(KeyId=key_id, CiphertextBlob=cipher_text)[ |
| 77 | "Plaintext" |
| 78 | ].decode() |
no outgoing calls