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

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

Encrypt搭配使用 Amazon SDK或 CLI

以下代码示例演示如何使用 Encrypt

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

CLI
Amazon CLI

示例 1:在 Linux 或 macOS 上对文件内容进行加密

以下encrypt命令演示了使用加密数据的推荐方法 Amazon CLI.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 \ --decode > ExampleEncryptedFile

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

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

示例 2:使用 Amazon CLI在 Windows 上加密数据

此示例与前一个示例相同,不同之处在于,它使用 certutil 工具代替 base64。此过程需要两个命令,如以下示例所示。

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob > C:\Temp\ExampleEncryptedFile.base64 certutil -decode C:\Temp\ExampleEncryptedFile.base64 C:\Temp\ExampleEncryptedFile

示例 3:使用非对称KMS密钥进行加密

以下encrypt命令显示如何使用非对称KMS密钥加密纯文本。--encryption-algorithm 参数是必需的。与所有encryptCLI命令一样,plaintext参数必须采用 base64 编码,或者您必须使用fileb://前缀,前缀告诉 Amazon CLI从文件中读取二进制数据。

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 \ --decode > ExampleEncryptedFile

此命令不生成任何输出。

  • 有关API详细信息,请参阅中的 “加密Amazon CLI 命令参考

Java
SDK适用于 Java 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参考

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 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 { 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?, path: String, ) { val decryptRequest = DecryptRequest { ciphertextBlob = encryptedDataVal keyId = keyIdVal } KmsClient { region = "us-west-2" }.use { kmsClient -> val decryptResponse = kmsClient.decrypt(decryptRequest) val myVal = decryptResponse.plaintext // Write the decrypted data to a file. if (myVal != null) { File(path).writeBytes(myVal) } } }
  • 有关API详细信息,请参阅中的 “加密Amazon SDK以供API参考 Kotlin。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client def encrypt(self, key_id): """ Encrypts text by using the specified key. :param key_id: The ARN or ID of the key to use for encryption. :return: The encrypted version of the text. """ text = input("Enter some text to encrypt: ") try: cipher_text = self.kms_client.encrypt( KeyId=key_id, Plaintext=text.encode() )["CiphertextBlob"] except ClientError as err: logger.error( "Couldn't encrypt text. Here's why: %s", err.response["Error"]["Message"], ) else: print(f"Your ciphertext is: {cipher_text}") return cipher_text
  • 有关API详细信息,请参阅中的 “加密Amazon SDK供参考 Python (Boto3) API。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 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详细信息,请参阅中的 “加密Amazon SDK for Ruby API参考

Rust
SDK对于 Rust
注意

还有更多相关信息 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供API参考 Rust

有关完整列表 Amazon SDK开发者指南和代码示例,请参阅使用 Amazon KMS 用一个 Amazon SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。