AWS KMS chaveiros ECDH - AWS Encryption SDK

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

AWS KMS chaveiros ECDH

Um chaveiro AWS KMS ECDH usa um acordo de chave assimétrica AWS KMS keyspara derivar uma chave de embalagem simétrica compartilhada entre duas partes. Primeiro, o chaveiro usa o algoritmo de acordo de chaves Elliptic Curve Diffie-Hellman (ECDH) para derivar um segredo compartilhado da chave privada no par de chaves KMS do remetente e da chave pública do destinatário. Em seguida, o chaveiro usa o segredo compartilhado para derivar a chave de empacotamento compartilhada que protege suas chaves de criptografia de dados. A função de derivação de chave que o AWS Encryption SDK usa (KDF_CTR_HMAC_SHA384) para derivar a chave de empacotamento compartilhada está em conformidade com as recomendações do NIST para derivação de chaves.

A função de derivação de chave retorna 64 bytes de material de chaveamento. Para garantir que ambas as partes usem o material de codificação correto, AWS Encryption SDK usam os primeiros 32 bytes como chave de compromisso e os últimos 32 bytes como chave de empacotamento compartilhada. Na descriptografia, se o chaveiro não puder reproduzir a mesma chave de compromisso e chave de encapsulamento compartilhada armazenadas no texto cifrado do cabeçalho da mensagem, a operação falhará. Por exemplo, se você criptografar dados com um chaveiro configurado com a chave privada de Alice e a chave pública de Bob, um chaveiro configurado com a chave privada de Bob e a chave pública de Alice reproduzirá a mesma chave de compromisso e chave de empacotamento compartilhada e poderá descriptografar os dados. Se a chave pública de Bob não for de um par de chaves KMS, Bob poderá criar um chaveiro ECDH bruto para descriptografar os dados.

O chaveiro AWS KMS ECDH criptografa os dados com uma chave simétrica usando o AES-GCM. A chave de dados é então criptografada em envelope com a chave de empacotamento compartilhada derivada usando o AES-GCM. Cada chaveiro AWS KMS ECDH pode ter apenas uma chave de embrulho compartilhada, mas você pode incluir vários chaveiros AWS KMS ECDH, sozinhos ou com outros chaveiros, em um chaveiro múltiplo.

Compatibilidade com linguagens de programação

O chaveiro AWS KMS ECDH foi introduzido na versão 1.5.0 da Biblioteca de Provedores de Material Criptográfico (MPL) e é suportado pelas seguintes linguagens e versões de programação:

  • Versão 3. x do AWS Encryption SDK for Java

  • Versão 4. x do AWS Encryption SDK para o.NET

  • Versão 4. x do AWS Encryption SDK for Python, quando usado com a dependência opcional do MPL.

  • Versão 1. x do AWS Encryption SDK para Rust

  • Versão 0.1. x ou posterior do AWS Encryption SDK for Go

Permissões necessárias para AWS KMS chaveiros ECDH

AWS Encryption SDK Não requer uma AWS conta e não depende de nenhum AWS serviço. No entanto, para usar um chaveiro AWS KMS ECDH, você precisa de uma AWS conta e das seguintes permissões mínimas AWS KMS keys no seu chaveiro. As permissões variam de acordo com o esquema de contrato de chaves que você usa.

Criando um AWS KMS chaveiro ECDH

Para criar um chaveiro AWS KMS ECDH que criptografe e descriptografe dados, você deve usar o esquema de contrato de chave. KmsPrivateKeyToStaticPublicKey Para inicializar um chaveiro AWS KMS ECDH com o esquema de contrato de KmsPrivateKeyToStaticPublicKey chaves, forneça os seguintes valores:

C# / .NET

O exemplo a seguir cria um chaveiro AWS KMS ECDH com a chave KMS do remetente, a chave pública do remetente e a chave pública do destinatário. Este exemplo usa o SenderPublicKey parâmetro opcional para fornecer a chave pública do remetente. Se você não fornecer a chave pública do remetente, o chaveiro liga AWS KMS para recuperar a chave pública do remetente. Os pares de chaves do remetente e do destinatário estão na ECC_NIST_P256 curva.

// Instantiate material providers var materialProviders = new MaterialProviders(new MaterialProvidersConfig()); // Must be DER-encoded X.509 public keys var BobPublicKey = new MemoryStream(new byte[] { }); var AlicePublicKey = new MemoryStream(new byte[] { }); // Create the AWS KMS ECDH static keyring var staticConfiguration = new KmsEcdhStaticConfigurations { KmsPrivateKeyToStaticPublicKey = new KmsPrivateKeyToStaticPublicKeyInput { SenderKmsIdentifier = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", SenderPublicKey = BobPublicKey, RecipientPublicKey = AlicePublicKey } }; var createKeyringInput = new CreateAwsKmsEcdhKeyringInput { CurveSpec = ECDHCurveSpec.ECC_NIST_P256, KmsClient = new AmazonKeyManagementServiceClient(), KeyAgreementScheme = staticConfiguration }; var keyring = materialProviders.CreateAwsKmsEcdhKeyring(createKeyringInput);
Java

O exemplo a seguir cria um chaveiro AWS KMS ECDH com a chave KMS do remetente, a chave pública do remetente e a chave pública do destinatário. Este exemplo usa o senderPublicKey parâmetro opcional para fornecer a chave pública do remetente. Se você não fornecer a chave pública do remetente, o chaveiro liga AWS KMS para recuperar a chave pública do remetente. Os pares de chaves do remetente e do destinatário estão na ECC_NIST_P256 curva.

// Retrieve public keys // Must be DER-encoded X.509 public keys ByteBuffer BobPublicKey = getPublicKeyBytes("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"); ByteBuffer AlicePublicKey = getPublicKeyBytes("arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321"); // Create the AWS KMS ECDH static keyring final CreateAwsKmsEcdhKeyringInput senderKeyringInput = CreateAwsKmsEcdhKeyringInput.builder() .kmsClient(KmsClient.create()) .curveSpec(ECDHCurveSpec.ECC_NIST_P256) .KeyAgreementScheme( KmsEcdhStaticConfigurations.builder() .KmsPrivateKeyToStaticPublicKey( KmsPrivateKeyToStaticPublicKeyInput.builder() .senderKmsIdentifier("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab") .senderPublicKey(BobPublicKey) .recipientPublicKey(AlicePublicKey) .build()).build()).build();
Python

O exemplo a seguir cria um chaveiro AWS KMS ECDH com a chave KMS do remetente, a chave pública do remetente e a chave pública do destinatário. Este exemplo usa o senderPublicKey parâmetro opcional para fornecer a chave pública do remetente. Se você não fornecer a chave pública do remetente, o chaveiro liga AWS KMS para recuperar a chave pública do remetente. Os pares de chaves do remetente e do destinatário estão na ECC_NIST_P256 curva.

import boto3 from aws_cryptographic_materialproviders.mpl.models import ( CreateAwsKmsEcdhKeyringInput, KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey, KmsPrivateKeyToStaticPublicKeyInput, ) from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models import ECDHCurveSpec # Instantiate the material providers library mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders( config=MaterialProvidersConfig() ) # Retrieve public keys # Must be DER-encoded X.509 public keys bob_public_key = get_public_key_bytes("arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab") alice_public_key = get_public_key_bytes("arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321") # Create the AWS KMS ECDH static keyring sender_keyring_input = CreateAwsKmsEcdhKeyringInput( kms_client = boto3.client('kms', region_name="us-west-2"), curve_spec = ECDHCurveSpec.ECC_NIST_P256, key_agreement_scheme = KmsEcdhStaticConfigurationsKmsPrivateKeyToStaticPublicKey( KmsPrivateKeyToStaticPublicKeyInput( sender_kms_identifier = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", sender_public_key = bob_public_key, recipient_public_key = alice_public_key, ) ) ) keyring = mat_prov.create_aws_kms_ecdh_keyring(sender_keyring_input)
Rust

O exemplo a seguir cria um chaveiro AWS KMS ECDH com a chave KMS do remetente, a chave pública do remetente e a chave pública do destinatário. Este exemplo usa o sender_public_key parâmetro opcional para fornecer a chave pública do remetente. Se você não fornecer a chave pública do remetente, o chaveiro liga AWS KMS para recuperar a chave pública do remetente.

// Instantiate the AWS Encryption SDK client let esdk_config = AwsEncryptionSdkConfig::builder().build()?; let esdk_client = esdk_client::Client::from_conf(esdk_config)?; // Create the AWS KMS client let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; let kms_client = aws_sdk_kms::Client::new(&sdk_config); // Optional: Create your encryption context let encryption_context = HashMap::from([ ("encryption".to_string(), "context".to_string()), ("is not".to_string(), "secret".to_string()), ("but adds".to_string(), "useful metadata".to_string()), ("that can help you".to_string(), "be confident that".to_string()), ("the data you are handling".to_string(), "is what you think it is".to_string()), ]); // Retrieve public keys // Must be DER-encoded X.509 keys let public_key_file_content_sender = std::fs::read_to_string(Path::new(EXAMPLE_KMS_ECC_PUBLIC_KEY_FILENAME_SENDER))?; let parsed_public_key_file_content_sender = parse(public_key_file_content_sender)?; let public_key_sender_utf8_bytes = parsed_public_key_file_content_sender.contents(); let public_key_file_content_recipient = std::fs::read_to_string(Path::new(EXAMPLE_KMS_ECC_PUBLIC_KEY_FILENAME_RECIPIENT))?; let parsed_public_key_file_content_recipient = parse(public_key_file_content_recipient)?; let public_key_recipient_utf8_bytes = parsed_public_key_file_content_recipient.contents(); // Create KmsPrivateKeyToStaticPublicKeyInput let kms_ecdh_static_configuration_input = KmsPrivateKeyToStaticPublicKeyInput::builder() .sender_kms_identifier(arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab) // Must be a UTF8 DER-encoded X.509 public key .sender_public_key(public_key_sender_utf8_bytes) // Must be a UTF8 DER-encoded X.509 public key .recipient_public_key(public_key_recipient_utf8_bytes) .build()?; let kms_ecdh_static_configuration = KmsEcdhStaticConfigurations::KmsPrivateKeyToStaticPublicKey(kms_ecdh_static_configuration_input); // Instantiate the material providers library let mpl_config = MaterialProvidersConfig::builder().build()?; let mpl = mpl_client::Client::from_conf(mpl_config)?; // Create AWS KMS ECDH keyring let kms_ecdh_keyring = mpl .create_aws_kms_ecdh_keyring() .kms_client(kms_client) .curve_spec(ecdh_curve_spec) .key_agreement_scheme(kms_ecdh_static_configuration) .send() .await?;
Go
import ( "context" mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated" mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes" client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated" esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/kms" ) // Instantiate the AWS Encryption SDK client encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{}) if err != nil { panic(err) } // Create an AWS KMS client cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic(err) } kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) { o.Region = KmsKeyRegion }) // Optional: Create an encryption context encryptionContext := map[string]string{ "encryption": "context", "is not": "secret", "but adds": "useful metadata", "that can help you": "be confident that", "the data you are handling": "is what you think it is", } // Retrieve public keys // Must be DER-encoded X.509 keys publicKeySender, err := utils.LoadPublicKeyFromPEM(kmsEccPublicKeyFileNameSender) if err != nil { panic(err) } publicKeyRecipient, err := utils.LoadPublicKeyFromPEM(kmsEccPublicKeyFileNameRecipient) if err != nil { panic(err) } // Create KmsPrivateKeyToStaticPublicKeyInput kmsEcdhStaticConfigurationInput := mpltypes.KmsPrivateKeyToStaticPublicKeyInput{ RecipientPublicKey: publicKeyRecipient, SenderKmsIdentifier: arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab, SenderPublicKey: publicKeySender, } kmsEcdhStaticConfiguration := &mpltypes.KmsEcdhStaticConfigurationsMemberKmsPrivateKeyToStaticPublicKey{ Value: kmsEcdhStaticConfigurationInput, } // Instantiate the material providers library matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{}) if err != nil { panic(err) } // Create AWS KMS ECDH keyring awsKmsEcdhKeyringInput := mpltypes.CreateAwsKmsEcdhKeyringInput{ CurveSpec: ecdhCurveSpec, KeyAgreementScheme: kmsEcdhStaticConfiguration, KmsClient: kmsClient, } awsKmsEcdhKeyring, err := matProv.CreateAwsKmsEcdhKeyring(context.Background(), awsKmsEcdhKeyringInput) if err != nil { panic(err) }

Criando um AWS KMS chaveiro de descoberta ECDH

Ao descriptografar, é uma prática recomendada especificar as chaves que eles podem usar. AWS Encryption SDK Para seguir essa prática recomendada, use um chaveiro AWS KMS ECDH com o esquema de contrato de KmsPrivateKeyToStaticPublicKey chaves. No entanto, você também pode criar um chaveiro de descoberta AWS KMS ECDH, ou seja, um chaveiro AWS KMS ECDH que pode descriptografar qualquer mensagem em que a chave pública do par de chaves KMS especificado corresponda à chave pública do destinatário armazenada no texto cifrado da mensagem.

Importante

Ao descriptografar mensagens usando o esquema de contrato de KmsPublicKeyDiscovery chave, você aceita todas as chaves públicas, independentemente de quem as possua.

Para inicializar um chaveiro AWS KMS ECDH com o esquema de contrato de KmsPublicKeyDiscovery chaves, forneça os seguintes valores:

  • AWS KMS key ID do destinatário

    Deve identificar um par de chaves KMS de curva elíptica (ECC) assimétrica recomendado pelo NIST com um valor de. KeyUsage KEY_AGREEMENT

  • Especificação da curva

    Identifica a especificação da curva elíptica no par de chaves KMS do destinatário.

    Valores válidos: ECC_NIST_P256, ECC_NIS_P384, ECC_NIST_P512

  • (Opcional) Uma lista de Tokens de Concessão

    Se você controlar o acesso à chave KMS em seu chaveiro AWS KMS ECDH com concessões, deverá fornecer todos os tokens de concessão necessários ao inicializar o chaveiro.

C# / .NET

O exemplo a seguir cria um chaveiro de descoberta AWS KMS ECDH com um par de chaves KMS na curva. ECC_NIST_P256 Você deve ter as DeriveSharedSecret permissões kms: GetPublicKey e kms: no par de chaves KMS especificado. Esse chaveiro pode descriptografar qualquer mensagem em que a chave pública do par de chaves KMS especificado corresponda à chave pública do destinatário armazenada no texto cifrado da mensagem.

// Instantiate material providers var materialProviders = new MaterialProviders(new MaterialProvidersConfig()); // Create the AWS KMS ECDH discovery keyring var discoveryConfiguration = new KmsEcdhStaticConfigurations { KmsPublicKeyDiscovery = new KmsPublicKeyDiscoveryInput { RecipientKmsIdentifier = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321" } }; var createKeyringInput = new CreateAwsKmsEcdhKeyringInput { CurveSpec = ECDHCurveSpec.ECC_NIST_P256, KmsClient = new AmazonKeyManagementServiceClient(), KeyAgreementScheme = discoveryConfiguration }; var keyring = materialProviders.CreateAwsKmsEcdhKeyring(createKeyringInput);
Java

O exemplo a seguir cria um chaveiro de descoberta AWS KMS ECDH com um par de chaves KMS na curva. ECC_NIST_P256 Você deve ter as DeriveSharedSecret permissões kms: GetPublicKey e kms: no par de chaves KMS especificado. Esse chaveiro pode descriptografar qualquer mensagem em que a chave pública do par de chaves KMS especificado corresponda à chave pública do destinatário armazenada no texto cifrado da mensagem.

// Create the AWS KMS ECDH discovery keyring final CreateAwsKmsEcdhKeyringInput recipientKeyringInput = CreateAwsKmsEcdhKeyringInput.builder() .kmsClient(KmsClient.create()) .curveSpec(ECDHCurveSpec.ECC_NIST_P256) .KeyAgreementScheme( KmsEcdhStaticConfigurations.builder() .KmsPublicKeyDiscovery( KmsPublicKeyDiscoveryInput.builder() .recipientKmsIdentifier("arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321").build() ).build()) .build();
Python

O exemplo a seguir cria um chaveiro de descoberta AWS KMS ECDH com um par de chaves KMS na curva. ECC_NIST_P256 Você deve ter as DeriveSharedSecret permissões kms: GetPublicKey e kms: no par de chaves KMS especificado. Esse chaveiro pode descriptografar qualquer mensagem em que a chave pública do par de chaves KMS especificado corresponda à chave pública do destinatário armazenada no texto cifrado da mensagem.

import boto3 from aws_cryptographic_materialproviders.mpl.models import ( CreateAwsKmsEcdhKeyringInput, KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery, KmsPublicKeyDiscoveryInput, ) from aws_cryptography_primitives.smithygenerated.aws_cryptography_primitives.models import ECDHCurveSpec # Instantiate the material providers library mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders( config=MaterialProvidersConfig() ) # Create the AWS KMS ECDH discovery keyring create_keyring_input = CreateAwsKmsEcdhKeyringInput( kms_client = boto3.client('kms', region_name="us-west-2"), curve_spec = ECDHCurveSpec.ECC_NIST_P256, key_agreement_scheme = KmsEcdhStaticConfigurationsKmsPublicKeyDiscovery( KmsPublicKeyDiscoveryInput( recipient_kms_identifier = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321", ) ) ) keyring = mat_prov.create_aws_kms_ecdh_keyring(create_keyring_input)
Rust
// Instantiate the AWS Encryption SDK client let esdk_config = AwsEncryptionSdkConfig::builder().build()?; let esdk_client = esdk_client::Client::from_conf(esdk_config)?; // Create the AWS KMS client let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; let kms_client = aws_sdk_kms::Client::new(&sdk_config); // Optional: Create your encryption context let encryption_context = HashMap::from([ ("encryption".to_string(), "context".to_string()), ("is not".to_string(), "secret".to_string()), ("but adds".to_string(), "useful metadata".to_string()), ("that can help you".to_string(), "be confident that".to_string()), ("the data you are handling".to_string(), "is what you think it is".to_string()), ]); // Create KmsPublicKeyDiscoveryInput let kms_ecdh_discovery_static_configuration_input = KmsPublicKeyDiscoveryInput::builder() .recipient_kms_identifier(ecc_recipient_key_arn) .build()?; let kms_ecdh_discovery_static_configuration = KmsEcdhStaticConfigurations::KmsPublicKeyDiscovery(kms_ecdh_discovery_static_configuration_input); // Instantiate the material providers library let mpl_config = MaterialProvidersConfig::builder().build()?; let mpl = mpl_client::Client::from_conf(mpl_config)?; // Create AWS KMS ECDH discovery keyring let kms_ecdh_discovery_keyring = mpl .create_aws_kms_ecdh_keyring() .kms_client(kms_client.clone()) .curve_spec(ecdh_curve_spec) .key_agreement_scheme(kms_ecdh_discovery_static_configuration) .send() .await?;
Go
import ( "context" mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated" mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes" client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated" esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/kms" ) // Instantiate the AWS Encryption SDK client encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{}) if err != nil { panic(err) } // Create an AWS KMS client cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic(err) } kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) { o.Region = KmsKeyRegion }) // Optional: Create an encryption context encryptionContext := map[string]string{ "encryption": "context", "is not": "secret", "but adds": "useful metadata", "that can help you": "be confident that", "the data you are handling": "is what you think it is", } // Create KmsPublicKeyDiscoveryInput kmsEcdhDiscoveryStaticConfigurationInput := mpltypes.KmsPublicKeyDiscoveryInput{ RecipientKmsIdentifier: eccRecipientKeyArn, } kmsEcdhDiscoveryStaticConfiguration := &mpltypes.KmsEcdhStaticConfigurationsMemberKmsPublicKeyDiscovery{ Value: kmsEcdhDiscoveryStaticConfigurationInput, } // Instantiate the material providers library matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{}) if err != nil { panic(err) } // Create AWS KMS ECDH discovery keyring awsKmsEcdhDiscoveryKeyringInput := mpltypes.CreateAwsKmsEcdhKeyringInput{ CurveSpec: ecdhCurveSpec, KeyAgreementScheme: kmsEcdhDiscoveryStaticConfiguration, KmsClient: kmsClient, } awsKmsEcdhDiscoveryKeyring, err := matProv.CreateAwsKmsEcdhKeyring(context.Background(), awsKmsEcdhDiscoveryKeyringInput) if err != nil { panic(err) }