MCPcopy Create free account
hub / github.com/awsdocs/aws-doc-sdk-examples / KeyEncrypt

Class KeyEncrypt

python/example_code/kms/key_encryption.py:21–177  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19
20# snippet-start:[python.example_code.kms.KeyEncrypt.decl]
21class 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()

Callers 3

kms_scenario.pyFile · 0.90
__init__Method · 0.90
key_encryptionFunction · 0.85

Calls

no outgoing calls

Tested by 1

__init__Method · 0.72