View a markdown version of this page

使用 加密 用 Amazon SDK 或 CLI - Amazon Key Management Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 加密 用 Amazon SDK 或 CLI

以下代码示例显示了如何使用 Encrypt。

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

CLI
Amazon CLI

示例 1:加密文件内容(Linux 和 macOS)

以下 encrypt 示例演示了使用加密数据的推荐方法 Amazon CLI。

aws kms encrypt \ --key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 --decode > ExampleEncryptedFile

该命令可以执行以下几项操作:

使用 --plaintext 参数来指示要加密的数据。此参数值必须采用 Base64 编码。的值 plaintext 参数必须采用 base64 编码,或者必须使用 fileb:// 前缀,它告诉 Amazon CLI 从文件中读取二进制数据。如果文件不在当前目录中,请键入文件的完整路径。例如:fileb:///var/tmp/ExamplePlaintextFile 或 fileb://C:\Temp\ExamplePlaintextFile。有关阅读的更多信息 Amazon 文件中的 CLI 参数值,请参阅 从文件加载参数 在 Amazon 命令行界面用户指南.使用 --output 和 --query 控制命令输出的参数。这些参数提取加密数据,称为 密文,来自命令的输出。有关控制输出的更多信息,请参见 控制命令输出 在 Amazon 命令行界面用户指南.使用 base64 将提取的输出解码为二进制数据的实用程序。成功返回的密文 encrypt 命令是 base64 编码的文本。必须先解码此文本,然后才能使用 Amazon CLI 对其进行解密。将二进制密文保存到文件中。命令的最后一部分 (> ExampleEncryptedFile) 将二进制密文保存到文件中以简化解密。有关使用以下命令的示例 Amazon 要解密数据的 CLI,请参阅解密示例。

此命令不生成任何输出。

示例 2:加密文件内容 (Windows)

以下 encrypt 示例与前一个相同,唯一的不同是它使用了 certutil 工具而不是 base64。此过程需要两个命令,如以下示例所示。

aws kms encrypt ^ --key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 ^ --plaintext fileb://ExamplePlaintextFile ^ --output text ^ --query CiphertextBlob > C:\Temp\ExampleEncryptedFile.base64

此命令不生成任何输出。base64 编码的密文保存到 C:\Temp\ExampleEncryptedFile.base64。

运行 certutil 命令。

certutil -decode C:\Temp\ExampleEncryptedFile.base64 C:\Temp\ExampleEncryptedFile

密文保存到 C:\Temp\ExampleEncryptedFile。

示例 3:使用非对称 KMS 密钥加密文件内容

以下 encrypt 示例显示如何使用非对称 KMS 密钥加密明文。--encryption-algorithm 参数是必需的。总而言之 encrypt CLI 命令, plaintext 参数必须采用 base64 编码,或者必须使用 fileb:// 前缀,它告诉 Amazon CLI 从文件中读取二进制数据。

aws kms encrypt \ --key-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 --decode > ExampleEncryptedFile

此命令不生成任何输出。

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 Encrypt。

Java
适用于 Java 的 SDK 2.x
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/** * Encrypts the given text asynchronously using the specified KMS client and key ID. * * @param keyId the ID of the KMS key to use for encryption * @param text the text to encrypt * @return a CompletableFuture that completes with the encrypted data as an SdkBytes object */ public CompletableFuture<SdkBytes> encryptDataAsync(String keyId, String text) { SdkBytes myBytes = SdkBytes.fromUtf8String(text); EncryptRequest encryptRequest = EncryptRequest.builder() .keyId(keyId) .plaintext(myBytes) .build(); CompletableFuture<EncryptResponse> responseFuture = getAsyncClient().encrypt(encryptRequest).toCompletableFuture(); return responseFuture.whenComplete((response, ex) -> { if (response != null) { String algorithm = response.encryptionAlgorithm().toString(); logger.info("The string was encrypted with algorithm {}.", algorithm); } else { throw new RuntimeException(ex); } }).thenApply(EncryptResponse::ciphertextBlob); }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API Reference》中的 Encrypt。

Kotlin
适用于 Kotlin 的 SDK
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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.fromEnvironment { 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 详细信息,请参阅《Amazon SDK for Kotlin API Reference》中的 Encrypt。

PHP
适用于 PHP 的 SDK
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/*** * @param string $keyId * @param string $text * @return Result */ public function encrypt(string $keyId, string $text) { try { return $this->client->encrypt([ 'KeyId' => $keyId, 'Plaintext' => $text, ]); }catch(KmsException $caught){ if($caught->getAwsErrorMessage() == "DisabledException"){ echo "The request was rejected because the specified KMS key is not enabled.\n"; } throw $caught; } }
  • 有关 API 详细信息,请参阅《适用于 PHP 的 Amazon SDK API Reference》中的 Encrypt。

Python
适用于 Python 的 SDK(Boto3)
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 encrypt(self, key_id: str, text: str) -> bytes: """ Encrypts text by using the specified key. :param key_id: The ARN or ID of the key to use for encryption. :param text: The text to encrypt. :return: The encrypted version of the text. """ try: response = self.kms_client.encrypt(KeyId=key_id, Plaintext=text.encode()) print( f"The string was encrypted with algorithm {response['EncryptionAlgorithm']}" ) return response["CiphertextBlob"] except ClientError as err: if err.response["Error"]["Code"] == "DisabledException": logger.error( "Could not encrypt because the key %s is disabled.", key_id ) else: logger.error( "Couldn't encrypt text. Here's why: %s", err.response["Error"]["Message"], ) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API Reference》中的 Encrypt。

Ruby
适用于 Ruby 的 SDK
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

require 'aws-sdk-kms' # v2: require 'aws-sdk' # ARN of the AWS KMS key. # # Replace the fictitious key ARN with a valid key ID keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab' text = '1234567890' client = Aws::KMS::Client.new(region: 'us-west-2') resp = client.encrypt({ key_id: keyId, plaintext: text }) # Display a readable version of the resulting encrypted blob. puts 'Blob:' puts resp.ciphertext_blob.unpack('H*')
  • 有关 API 详细信息,请参阅《适用于 Ruby 的 Amazon SDK API Reference》中的 Encrypt。

Rust
适用于 Rust 的 SDK
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

async fn encrypt_string( verbose: bool, client: &Client, text: &str, key: &str, out_file: &str, ) -> Result<(), Error> { let blob = Blob::new(text.as_bytes()); let resp = client.encrypt().key_id(key).plaintext(blob).send().await?; // Did we get an encrypted blob? let blob = resp.ciphertext_blob.expect("Could not get encrypted text"); let bytes = blob.as_ref(); let s = base64::encode(bytes); let mut ofile = File::create(out_file).expect("unable to create file"); ofile.write_all(s.as_bytes()).expect("unable to write"); if verbose { println!("Wrote the following to {:?}", out_file); println!("{}", s); } Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API Reference》中的 Encrypt。

SAP ABAP
适用于 SAP ABAP 的 SDK
注意

还有更多关于 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

TRY. " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab' " iv_plaintext contains the data to encrypt oo_result = lo_kms->encrypt( iv_keyid = iv_key_id iv_plaintext = iv_plaintext ). MESSAGE 'Text encrypted successfully.' TYPE 'I'. CATCH /aws1/cx_kmsdisabledexception. MESSAGE 'The key is disabled.' TYPE 'E'. CATCH /aws1/cx_kmsnotfoundexception. MESSAGE 'Key not found.' TYPE 'E'. CATCH /aws1/cx_kmskmsinternalex. MESSAGE 'An internal error occurred.' TYPE 'E'. ENDTRY.
  • 有关 API 的详细信息,请参阅 加密 在 Amazon 适用于 SAP 的 SDK ABAP API 参考。

如需查看完整清单 Amazon SDK 开发者指南和代码示例,请参阅 将此服务与 Amazon SDK。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。