AWSSDKAWS KMS key を使用して暗号文をある暗号文から別の暗号文に再暗号化する - AWSSDK コードサンプル

AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWSSDKAWS KMS key を使用して暗号文をある暗号文から別の暗号文に再暗号化する

次のコード例は、1 つの KMS キーから別の KMS キーに暗号テキストを再暗号化する方法を示しています。

Go
SDK for Go V2
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/kms" ) // KMSReEncryptAPI defines the interface for the ReEncrypt function. // We use this interface to test the function using a mocked service. type KMSReEncryptAPI interface { ReEncrypt(ctx context.Context, params *kms.ReEncryptInput, optFns ...func(*kms.Options)) (*kms.ReEncryptOutput, error) } // ReEncryptText reencrypts some text using a new AWS Key Management Service (AWS KMS) key (KMS key). // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If success, a ReEncryptOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to ReEncrypt. func ReEncryptText(c context.Context, api KMSReEncryptAPI, input *kms.ReEncryptInput) (*kms.ReEncryptOutput, error) { return api.ReEncrypt(c, input) } func main() { keyID := flag.String("k", "", "The ID of a KMS key") data := flag.String("d", "", "The data to reencrypt, as a string") flag.Parse() if *keyID == "" || *data == "" { fmt.Println("You must supply the ID of a KMS key and data") fmt.Println("-k KEY-ID -d DATA") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := kms.NewFromConfig(cfg) blob := []byte(*data) input := &kms.ReEncryptInput{ CiphertextBlob: blob, DestinationKeyId: keyID, } result, err := ReEncryptText(context.TODO(), client, input) if err != nil { fmt.Println("Got error reencrypting data:") fmt.Println(err) return } fmt.Println("Blob (base-64 byte array):") fmt.Println(result.CiphertextBlob) }
  • API の詳細については、AWS SDK for GoAPI ReEncryptリファレンスのを参照してください

Python
SDK for Python (Boto3)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client def re_encrypt(self, source_key_id, cipher_text): """ Takes ciphertext previously encrypted with one key and reencrypt it by using another key. :param source_key_id: The ARN or ID of the original key used to encrypt the ciphertext. :param cipher_text: The encrypted ciphertext. :return: The ciphertext encrypted by the second key. """ destination_key_id = input( f"Your ciphertext is currently encrypted with key {source_key_id}. " f"Enter another key ID or ARN to reencrypt it: ") if destination_key_id != '': try: cipher_text = self.kms_client.re_encrypt( SourceKeyId=source_key_id, DestinationKeyId=destination_key_id, CiphertextBlob=cipher_text)['CiphertextBlob'] except ClientError as err: logger.error( "Couldn't reencrypt your ciphertext. Here's why: %s", err.response['Error']['Message']) else: print(f"Reencrypted your ciphertext as: {cipher_text}") return cipher_text else: print("Skipping reencryption demo.")
  • API の詳細については、「AWSSDK for Python (Boto3) API リファレンス」のを参照してくださいReEncrypt

Rust
SDK for Rust
注記

これはプレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があり、本稼働環境では使用しないでください。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

async fn reencrypt_string( verbose: bool, client: &Client, input_file: &str, output_file: &str, first_key: &str, new_key: &str, ) -> Result<(), Error> { // Get blob from input file // 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(input_file) .map(|input_file| base64::decode(input_file).expect("invalid base 64")) .map(Blob::new); let resp = client .re_encrypt() .ciphertext_blob(data.unwrap()) .source_key_id(first_key) .destination_key_id(new_key) .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 o = &output_file; let mut ofile = File::create(o).expect("unable to create file"); ofile.write_all(s.as_bytes()).expect("unable to write"); if verbose { println!("Wrote the following to {}:", output_file); println!("{}", s); } else { println!("Wrote base64-encoded output to {}", output_file); } Ok(()) }
  • API の詳細については、SDK for Rust API リファレンスReEncryptの「AWSSDK for Rust API リファレンス」を参照してください。