Decrypt 搭配 AWS SDK 或 CLI 使用 - AWS Key Management Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Decrypt 搭配 AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 Decrypt

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

CLI
AWS CLI

範例 1:使用對稱 KMS 金鑰 (Linux 和 macOS) 解密加密的訊息

下列decrypt命令範例示範使用 CLI AWS 解密資料的建議方法。此版本示範如何在對稱 KMS 金鑰下解密資料。

在 file.In 中提供 --ciphertext-blob 參數值的加密文字,使用 fileb://字首,告知 CLI 從二進位檔案讀取資料。如果檔案不在目前的目錄中,請輸入檔案的完整路徑。如需從 檔案讀取 AWS CLI 參數值的詳細資訊, 請參閱 Command Line Interface AWS 使用者指南中的從檔案 <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html> 載入 CLI 參數,以及 AWS Command Line Tool 部落格中的本機檔案參數最佳實務 <https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/>。指定 KMS 金鑰以解密加密文字。使用對稱 KMS 金鑰解密時,不需要 --key-id 參數。 AWS KMS 可以取得用於加密加密加密加密加密文字中中繼資料之 KMS 金鑰的金鑰 ID。 AWS 但是指定您正在使用的 KMS 金鑰永遠是最佳實務。此實務可確保您使用您打算使用的 KMS 金鑰,並防止您不信任的 KMS 金鑰意外解密加密文字。請求純文字輸出做為文字值。 --query 參數會告知 CLI 僅從輸出取得 Plaintext 欄位的值。--output 參數會以文字傳回輸出。Base64 將純文字解碼,並將其儲存在檔案中。下列範例會將 Plaintext 參數的值 (|) 輸送至 Base64 公用程式,以將其解碼。然後,它會將解碼後的輸出重新導向 (>) 至 ExamplePlaintext 檔案。

執行此命令之前,請將範例金鑰 ID 取代為來自您 AWS 帳戶的有效金鑰 ID。

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --output text \ --query Plaintext | base64 \ --decode > ExamplePlaintextFile

此命令不會產生輸出。來自 decrypt命令的輸出經過 base64 解碼,並儲存在 檔案中。

如需詳細資訊,請參閱 AWS Key Management Service API 參考中的解密

範例 2:使用對稱 KMS 金鑰解密加密的訊息 (Windows 命令提示)

下列範例與上一個範例相同,但它使用 certutil公用程式來對純文字資料進行 Base64-decode。此程序需要兩個命令,如下列範例所示。

執行此命令之前,請將範例金鑰 ID 取代為來自您 AWS 帳戶的有效金鑰 ID。

aws kms decrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^ --output text ^ --query Plaintext > ExamplePlaintextFile.base64

執行 certutil 命令。

certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile

輸出:

Input Length = 18 Output Length = 12 CertUtil: -decode command completed successfully.

如需詳細資訊,請參閱 AWS Key Management Service API 參考中的解密

範例 3:使用非對稱 KMS 金鑰 (Linux 和 macOS) 解密加密的訊息

下列decrypt命令範例示範如何解密 RSA 非對稱 KMS 金鑰下加密的資料。

使用非對稱 KMS 金鑰時,需要指定用於加密純文字的演算法的 encryption-algorithm 參數。

執行此命令之前,請將範例金鑰 ID 取代為來自您 AWS 帳戶的有效金鑰 ID。

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --output text \ --query Plaintext | base64 \ --decode > ExamplePlaintextFile

此命令不會產生輸出。來自 decrypt命令的輸出經過 base64 解碼,並儲存在 檔案中。

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的 AWS KMS 中的非對稱金鑰。 AWS

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的解密

Java
SDK for Java 2.x
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Asynchronously decrypts the given encrypted data using the specified key ID. * * @param encryptedData The encrypted data to be decrypted. * @param keyId The ID of the key to be used for decryption. * @return A CompletableFuture that, when completed, will contain the decrypted data as a String. * If an error occurs during the decryption process, the CompletableFuture will complete * exceptionally with the error, and the method will return an empty String. */ public CompletableFuture<String> decryptDataAsync(SdkBytes encryptedData, String keyId) { DecryptRequest decryptRequest = DecryptRequest.builder() .ciphertextBlob(encryptedData) .keyId(keyId) .build(); CompletableFuture<DecryptResponse> responseFuture = getAsyncClient().decrypt(decryptRequest); responseFuture.whenComplete((decryptResponse, exception) -> { if (exception == null) { logger.info("Data decrypted successfully for key ID: " + keyId); } else { if (exception instanceof KmsException kmsEx) { throw new RuntimeException("KMS error occurred while decrypting data: " + kmsEx.getMessage(), kmsEx); } else { throw new RuntimeException("An unexpected error occurred while decrypting data: " + exception.getMessage(), exception); } } }); return responseFuture.thenApply(decryptResponse -> decryptResponse.plaintext().asString(StandardCharsets.UTF_8)); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考中的解密。

Kotlin
SDK for Kotlin
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun encryptData(keyIdValue: String): ByteArray? { val text = "This is the text to encrypt by using the AWS KMS Service" val myBytes: ByteArray = text.toByteArray() val encryptRequest = EncryptRequest { keyId = keyIdValue plaintext = myBytes } KmsClient { region = "us-west-2" }.use { kmsClient -> val response = kmsClient.encrypt(encryptRequest) val algorithm: String = response.encryptionAlgorithm.toString() println("The encryption algorithm is $algorithm") // Return the encrypted data. return response.ciphertextBlob } } suspend fun decryptData( encryptedDataVal: ByteArray?, keyIdVal: String?, ) { val decryptRequest = DecryptRequest { ciphertextBlob = encryptedDataVal keyId = keyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> val decryptResponse = kmsClient.decrypt(decryptRequest) val myVal = decryptResponse.plaintext // Print the decrypted data. print(myVal) } }
  • 如需 API 詳細資訊,請參閱適用於 AWS Kotlin 的 SDK API 參考中的解密

PHP
SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/*** * @param string $keyId * @param string $ciphertext * @param string $algorithm * @return Result */ public function decrypt(string $keyId, string $ciphertext, string $algorithm = "SYMMETRIC_DEFAULT") { try{ return $this->client->decrypt([ 'CiphertextBlob' => $ciphertext, 'EncryptionAlgorithm' => $algorithm, 'KeyId' => $keyId, ]); }catch(KmsException $caught){ echo "There was a problem decrypting the data: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考中的解密。

Python
SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client @classmethod def from_client(cls) -> "KeyEncrypt": """ Creates a KeyEncrypt instance with a default KMS client. :return: An instance of KeyEncrypt initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def decrypt(self, key_id: str, cipher_text: str) -> bytes: """ Decrypts text previously encrypted with a key. :param key_id: The ARN or ID of the key used to decrypt the data. :param cipher_text: The encrypted text to decrypt. :return: The decrypted text. """ try: return self.kms_client.decrypt(KeyId=key_id, CiphertextBlob=cipher_text)[ "Plaintext" ] except ClientError as err: logger.error( "Couldn't decrypt your ciphertext. Here's why: %s", err.response["Error"]["Message"], ) raise
  • 如需 API 詳細資訊,請參閱 SDK AWS for Python (Boto3) API 參考中的解密

Ruby
SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

require 'aws-sdk-kms' # v2: require 'aws-sdk' # Decrypted blob blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1' blob_packed = [blob].pack('H*') client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.decrypt({ ciphertext_blob: blob_packed }) puts 'Raw text: ' puts resp.plaintext
  • 如需 API 詳細資訊,請參閱 AWS SDK for Ruby API 參考中的解密

Rust
SDK for Rust
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

async fn decrypt_key(client: &Client, key: &str, filename: &str) -> Result<(), Error> { // Open input text file and get contents as a string // input is a base-64 encoded string, so decode it: let data = fs::read_to_string(filename) .map(|input| { base64::decode(input).expect("Input file does not contain valid base 64 characters.") }) .map(Blob::new); let resp = client .decrypt() .key_id(key) .ciphertext_blob(data.unwrap()) .send() .await?; let inner = resp.plaintext.unwrap(); let bytes = inner.as_ref(); let s = String::from_utf8(bytes.to_vec()).expect("Could not convert to UTF-8"); println!(); println!("Decoded string:"); println!("{}", s); Ok(()) }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Rust API 參考中的解密

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 將此服務與 搭配使用 AWS SDK。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。