Cifrar y descifrar claves de datos
Los ejemplos de este tema utilizan las operaciones Encrypt, Decrypt y ReEncrypt de la API de AWS KMS.
Estas operaciones están diseñadas para cifrar y descifrar claves de datos. Utilizan una AWS KMS keys en las operaciones de cifrado y no pueden aceptar más de 4 KB (4 096 bytes) de datos. Aunque es posible utilizarlas para cifrar pequeñas cantidades de datos como, por ejemplo, una contraseña o una clave RSA, no se han diseñado para cifrar los datos de las aplicaciones.
Para cifrar los datos de las aplicaciones, utilice las características de cifrado del lado del servidor de un servicio de AWS o una biblioteca de cifrado del lado del cliente, como el AWS Encryption SDK o el cliente de cifrado de Amazon S3.
Cifrar una clave de datos
La operación Encrypt se ha diseñado para cifrar claves de datos, pero no se utiliza con frecuencia. Las operaciones GenerateDataKey y GenerateDataKeyWithoutPlaintext devuelven claves de datos cifradas. Puede utilizar este método cuando mueva datos cifrados a una región diferente y desee cifrar su clave de datos con una clave KMS en la nueva región.
En los idiomas que requieren un objeto cliente, estos ejemplos usan el objeto cliente de AWS KMS que ha creado en Crear un cliente.
- Java
-
Para obtener más detalles, consulte el método de cifrado en la Referencia de la API de AWS SDK for Java.
// Encrypt a data key
//
// Replace the following example key ARN with any valid key identfier
String keyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
ByteBuffer plaintext = ByteBuffer.wrap(new byte[]{1,2,3,4,5,6,7,8,9,0});
EncryptRequest req = new EncryptRequest().withKeyId(keyId).withPlaintext(plaintext);
ByteBuffer ciphertext = kmsClient.encrypt(req).getCiphertextBlob();
- C#
-
Para obtener más información, consulte el método Encrypt en el AWS SDK for .NET.
// Encrypt a data key
//
// Replace the following example key ARN with any valid key identfier
String keyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
MemoryStream plaintext = new MemoryStream();
plaintext.Write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }, 0, 10);
EncryptRequest encryptRequest = new EncryptRequest()
{
KeyId = keyId,
Plaintext = plaintext
};
MemoryStream ciphertext = kmsClient.Encrypt(encryptRequest).CiphertextBlob;
- Python
-
Para obtener más información, consulte el método encrypt en la AWS SDK for Python (Boto3).
# Encrypt a data key
# Replace the following example key ARN with any valid key identfier
key_id = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
plaintext = b'\x01\x02\x03\x04\x05\x06\x07\x08\x09\x00'
response = kms_client.encrypt(
KeyId=key_id,
Plaintext=plaintext
)
ciphertext = response['CiphertextBlob']
- Ruby
-
Para obtener más información, consulte el método de instancia encrypt en el AWS SDK for Ruby.
# Encrypt a data key
# Replace the following example key ARN with any valid key identfier
key_id = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
plaintext = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x00"
response = kmsClient.encrypt({
key_id: key_id,
plaintext: plaintext
})
ciphertext = response.ciphertext_blob
- PHP
-
Para obtener más información, consulte el método Encrypt en el AWS SDK for PHP.
// Encrypt a data key
//
// Replace the following example key ARN with any valid key identfier
$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$message = pack('c*',1,2,3,4,5,6,7,8,9,0);
$result = $KmsClient->encrypt([
'KeyId' => $keyId,
'Plaintext' => $message,
]);
$ciphertext = $result['CiphertextBlob'];
- Node.js
Para obtener más detalles, consulte.cifrar propiedad en la SDK for JavaScript in Node.js. de AWS.
// Encrypt a data key
//
// Replace the following example key ARN with any valid key identfier
const KeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
const Plaintext = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
kmsClient.encrypt({ KeyId, Plaintext }, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else {
const { CiphertextBlob } = data;
...
}
});
- PowerShell
Para cifrar una clave de datos en una clave KMS, utilice el cmdlet Invoke-KMSEncrypt. Devuelve el texto cifrado como un objeto MemoryStream
(System.IO.MemoryStream). Puede utilizar el objeto MemoryStream
como entrada para el cmdlet Invoke-KMSDecrypt.
AWS KMS también devuelve claves de datos como objetos MemoryStream
. En este ejemplo, para simular una clave de datos de texto sin formato, creamos una matriz de bytes y la escribimos en un objeto MemoryStream
.
Tenga en cuenta que el parámetro Plaintext
de Invoke-KMSEncrypt
toma una matriz de bytes (byte[]
); no requiere un objeto MemoryStream
. A partir de la versión 4.0 de AWSpowerShell, los parámetros de todos los módulos de AWSpowerShell que toman matrices de bytes y objetos MemoryStream
aceptan matrices de bytes, objetos MemoryStream
, cadenas, matrices de cadenas y objetos FileInfo
(System.IO.FileInfo). Puede pasar cualquiera de estos tipos a Invoke-KMSEncrypt
.
# Encrypt a data key
# Replace the following example key ARN with any valid key identfier
$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
# Simulate a data key
# Create a byte array
[byte[]] $bytes = 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
# Create a MemoryStream
$plaintext = [System.IO.MemoryStream]::new()
# Add the byte array to the MemoryStream
$plaintext.Write($bytes, 0, $bytes.length)
# Encrypt the simulated data key
$response = Invoke-KMSEncrypt -KeyId $keyId -Plaintext $plaintext
# Get the ciphertext from the response
$ciphertext = $response.CiphertextBlob
Para utilizar el AWS KMS PowerShell, instale el módulo AWS.Tools.KeyManagementService. Para obtener más información, consulte la Guía del usuario de AWS Tools for Windows PowerShell.
Descifrando una clave de datos
Para descifrar una clave de datos, use la operación Decrypt.
El ciphertextBlob
que especifique debe ser el valor del campo CiphertextBlob
de una respuesta GenerateDataKey, GenerateDataKeyWithoutPlaintext o Encrypt, o el campo PrivateKeyCiphertextBlob
de una respuesta GenerateDataKeyPair o GenerateDataKeyPairWithoutPlaintext. También puede utilizar la operación Decrypt
para descifrar los datos cifrados fuera de AWS KMS por la clave pública en una clave KMS asimétrica.
El parámetro KeyId
no es necesario al descifrar con claves de cifrado KMS simétricas. AWS KMS puede obtener la clave KMS que se usó para cifrar los datos de los metadatos en el blob de texto cifrado. Pero siempre es una práctica recomendada especificar la clave KMS que está utilizando. Esta práctica garantiza que utilice la clave KMS deseada y le impide descifrar inadvertidamente un texto cifrado utilizando una clave KMS en la que no confía.
En los idiomas que requieren un objeto cliente, estos ejemplos usan el objeto cliente de AWS KMS que ha creado en Crear un cliente.
- Java
-
Para obtener más detalles, consulte el método de descifrado en la Referencia de la API de AWS SDK for Java.
// Decrypt a data key
//
// Replace the following example key ARN with any valid key identfier
String keyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
ByteBuffer ciphertextBlob = Place your ciphertext here
;
DecryptRequest req = new DecryptRequest().withCiphertextBlob(ciphertextBlob).withKeyId(keyId);
ByteBuffer plainText = kmsClient.decrypt(req).getPlaintext();
- C#
-
Para obtener más información, consulte el método Decrypt en el AWS SDK for .NET.
// Decrypt a data key
//
// Replace the following example key ARN with any valid key identfier
String keyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
MemoryStream ciphertextBlob = new MemoryStream();
// Write ciphertext to memory stream
DecryptRequest decryptRequest = new DecryptRequest()
{
CiphertextBlob = ciphertextBlob,
KeyId = keyId
};
MemoryStream plainText = kmsClient.Decrypt(decryptRequest).Plaintext;
- Python
-
Para obtener más información, consulte el método decrypt en la AWS SDK for Python (Boto3).
# Decrypt a data key
# Replace the following example key ARN with any valid key identfier
key_id = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
ciphertext = 'Place your ciphertext here
'
response = kms_client.decrypt(
CiphertextBlob=ciphertext,
KeyId=key_id
)
plaintext = response['Plaintext']
- Ruby
-
Para obtener más información, consulte el método de instancia decrypt en el AWS SDK for Ruby.
# Decrypt a data key
# Replace the following example key ARN with any valid key identfier
key_id = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
ciphertext = 'Place your ciphertext here
'
ciphertext_packed = [ciphertext].pack("H*")
response = kmsClient.decrypt({
ciphertext_blob: ciphertext_packed,
key_id: key_id
})
plaintext = response.plaintext
- PHP
-
Para obtener más información, consulte el método Decrypt en el AWS SDK for PHP.
// Decrypt a data key
//
// Replace the following example key ARN with any valid key identfier
$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$ciphertext = 'Place your cipher text blob here
';
$result = $KmsClient->decrypt([
'CiphertextBlob' => $ciphertext,
'KeyId' => $keyId,
]);
$plaintext = $result['Plaintext'];
- Node.js
Para obtener más detalles, consulte la propiedad de cifrado en la SDK for JavaScript en Node.js de AWS.
// Decrypt a data key
//
// Replace the following example key ARN with any valid key identfier
const KeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
const CiphertextBlob = 'Place your cipher text blob here';
kmsClient.decrypt({ CiphertextBlob, KeyId }, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else {
const { Plaintext } = data;
...
}
});
- PowerShell
Para descifrar una clave de datos, utilice el cmdlet Invoke-KMSEncrypt.
Este cmdlet devuelve el texto sin formato como un objeto MemoryStream
(System.IO.MemoryStream). Para convertirlo en una matriz de bytes, utilice cmdlets o funciones que conviertan objetos MemoryStream
en matrices de bytes, como las funciones del módulo Convert.
Dado que este ejemplo utiliza el texto cifrado devuelto por un cmdlet de cifrado de AWS KMS, utiliza un objeto MemoryStream
para el valor del parámetro CiphertextBlob
. Sin embargo, el parámetro CiphertextBlob
de Invoke-KMSDecrypt
toma una matriz de bytes (byte[]
); no requiere un objeto MemoryStream
. A partir de la versión 4.0 de AWSpowerShell, los parámetros de todos los módulos de AWSpowerShell que toman matrices de bytes y objetos MemoryStream
aceptan matrices de bytes, objetos MemoryStream
, cadenas, matrices de cadenas y objetos FileInfo
(System.IO.FileInfo). Puede pasar cualquiera de estos tipos a Invoke-KMSDecrypt
.
# Decrypt a data key
# Replace the following example key ARN with any valid key identfier
$keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
[System.IO.MemoryStream]$ciphertext = Read-Host 'Place your cipher text blob here'
$response = Invoke-KMSDecrypt -CiphertextBlob $ciphertext -KeyId $keyId
$plaintext = $response.Plaintext
Para utilizar el AWS KMS PowerShell, instale el módulo AWS.Tools.KeyManagementService. Para obtener más información, consulte la Guía del usuario de AWS Tools for Windows PowerShell.
Volver a cifrar una clave de datos con otra AWS KMS key
Para descifrar una clave de datos cifrada y volver a cifrar inmediatamente la clave de datos con una AWS KMS key distinta, utilice la operación ReEncrypt. Las operaciones se realizan en su totalidad en el servidor en AWS KMS, por lo que su texto no cifrado nunca se expondrá fuera de AWS KMS.
El ciphertextBlob
que especifique debe ser el valor del campo CiphertextBlob
de una respuesta GenerateDataKey, GenerateDataKeyWithoutPlaintext o Encrypt, o el campo PrivateKeyCiphertextBlob
de una respuesta GenerateDataKeyPair o GenerateDataKeyPairWithoutPlaintext. También puede utilizar la operación ReEncrypt
para volver a cifrar los datos cifrados fuera de AWS KMS por la clave pública en una clave KMS asimétrica.
El parámetro SourceKeyId
no es necesario al volver a cifrar con claves simétricas KMS de codificación. AWS KMS puede obtener la clave KMS que se usó para cifrar los datos de los metadatos en el blob de texto cifrado. Pero siempre es una práctica recomendada especificar la clave KMS que está utilizando. Esta práctica garantiza que utilice la clave KMS deseada y le impide descifrar inadvertidamente un texto cifrado utilizando una clave KMS en la que no confía.
En los idiomas que requieren un objeto cliente, estos ejemplos usan el objeto cliente de AWS KMS que ha creado en Crear un cliente.
- Java
-
Para obtener más detalles, consulte el método reEncrypt en la Referencia de la API de la AWS SDK for Java.
// Re-encrypt a data key
ByteBuffer sourceCiphertextBlob = Place your ciphertext here
;
// Replace the following example key ARNs with valid key identfiers
String sourceKeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
String destinationKeyId = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321";
ReEncryptRequest req = new ReEncryptRequest();
req.setCiphertextBlob(sourceCiphertextBlob);
req.setSourceKeyId(sourceKeyId);
req.setDestinationKeyId(destinationKeyId);
ByteBuffer destinationCipherTextBlob = kmsClient.reEncrypt(req).getCiphertextBlob();
- C#
-
Para obtener más información, consulte el método ReEncrypt en el AWS SDK for .NET.
// Re-encrypt a data key
MemoryStream sourceCiphertextBlob = new MemoryStream();
// Write ciphertext to memory stream
// Replace the following example key ARNs with valid key identfiers
String sourceKeyId = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
String destinationKeyId = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321";
ReEncryptRequest reEncryptRequest = new ReEncryptRequest()
{
CiphertextBlob = sourceCiphertextBlob,
SourceKeyId = sourceKeyId,
DestinationKeyId = destinationKeyId
};
MemoryStream destinationCipherTextBlob = kmsClient.ReEncrypt(reEncryptRequest).CiphertextBlob;
- Python
-
Para obtener más información, consulte el método re_encrypt
en AWS SDK for Python (Boto3).
# Re-encrypt a data key
ciphertext = 'Place your ciphertext here
'
# Replace the following example key ARNs with valid key identfiers
source_key_id = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
destination_key_id = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321'
response = kms_client.re_encrypt(
CiphertextBlob=ciphertext,
SourceKeyId=source_key_id,
DestinationKeyId=destination_key_id
)
destination_ciphertext_blob = response['CiphertextBlob']
- Ruby
-
Para obtener más información, consulte el método de instancia re_encrypt
en AWS SDK for Ruby.
# Re-encrypt a data key
ciphertext = 'Place your ciphertext here
'
ciphertext_packed = [ciphertext].pack("H*")
# Replace the following example key ARNs with valid key identfiers
source_key_id = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
destination_key_id = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321'
response = kmsClient.re_encrypt({
ciphertext_blob: ciphertext_packed,
source_key_id: source_key_id,
destination_key_id: destination_key_id
})
destination_ciphertext_blob = response.ciphertext_blob.unpack('H*')
- PHP
-
Para obtener más información, consulte el método ReEncrypt en el AWS SDK for PHP.
// Re-encrypt a data key
$ciphertextBlob = 'Place your ciphertext here
';
// Replace the following example key ARNs with valid key identfiers
$sourceKeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
$destinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321';
$result = $KmsClient->reEncrypt([
'CiphertextBlob' => $ciphertextBlob,
'SourceKeyId' => $sourceKeyId,
'DestinationKeyId' => $destinationKeyId,
]);
- Node.js
Para obtener más detalles, consulte la propiedad reEncrypt en la SDK for JavaScript en Node.js de AWS.
// Re-encrypt a data key
const CiphertextBlob = 'Place your cipher text blob here';
// Replace the following example key ARNs with valid key identfiers
const SourceKeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab';
const DestinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321';
kmsClient.reEncrypt({ CiphertextBlob, SourceKeyId, DestinationKeyId }, (err, data) => {
...
});
- PowerShell
Para volver a cifrar un texto cifrado en la misma clave KMS o en otra diferente, utilice el cmdlet Invoke-KMSReencrypt.
Dado que este ejemplo utiliza el texto cifrado devuelto por un cmdlet de cifrado de AWS KMS, utiliza un objeto MemoryStream
para el valor del parámetro CiphertextBlob
. Sin embargo, el parámetro CiphertextBlob
de Invoke-KMSReEncrypt
toma una matriz de bytes (byte[]
); no requiere un objeto MemoryStream
. A partir de la versión 4.0 de AWSpowerShell, los parámetros de todos los módulos de AWSpowerShell que toman matrices de bytes y objetos MemoryStream
aceptan matrices de bytes, objetos MemoryStream
, cadenas, matrices de cadenas y objetos FileInfo
(System.IO.FileInfo). Puede pasar cualquiera de estos tipos a Invoke-KMSReEncrypt
.
# Re-encrypt a data key
[System.IO.MemoryStream]$ciphertextBlob = Read-Host 'Place your cipher text blob here'
# Replace the following example key ARNs with valid key identfiers
$sourceKeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
$destinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321'
$response = Invoke-KMSReEncrypt -Ciphertext $ciphertextBlob -SourceKeyId $sourceKeyId -DestinationKeyId $destinationKeyId
$reEncryptedCiphertext = $response.CiphertextBlob
Para utilizar el AWS KMS PowerShell, instale el módulo AWS.Tools.KeyManagementService. Para obtener más información, consulte la Guía del usuario de AWS Tools for Windows PowerShell.