Security News
PyPI Introduces Digital Attestations to Strengthen Python Package Security
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
@aws-sdk/client-kms
Advanced tools
AWS SDK for JavaScript Kms Client for Node.js, Browser and React Native
@aws-sdk/client-kms is an AWS SDK for JavaScript package that allows you to interact with the AWS Key Management Service (KMS). This service enables you to create and manage cryptographic keys and control their use across a wide range of AWS services and in your applications.
Create a Key
This feature allows you to create a new KMS key. The code sample demonstrates how to create a key with a description, usage type, and origin.
const { KMSClient, CreateKeyCommand } = require('@aws-sdk/client-kms');
const client = new KMSClient({ region: 'us-west-2' });
const command = new CreateKeyCommand({
Description: 'My test key',
KeyUsage: 'ENCRYPT_DECRYPT',
Origin: 'AWS_KMS'
});
client.send(command).then(
(data) => console.log('Key Created:', data.KeyMetadata.KeyId),
(error) => console.error('Error:', error)
);
Encrypt Data
This feature allows you to encrypt data using a specified KMS key. The code sample demonstrates how to encrypt a plaintext string.
const { KMSClient, EncryptCommand } = require('@aws-sdk/client-kms');
const client = new KMSClient({ region: 'us-west-2' });
const command = new EncryptCommand({
KeyId: 'your-key-id',
Plaintext: Buffer.from('Hello, World!')
});
client.send(command).then(
(data) => console.log('Encrypted Data:', data.CiphertextBlob.toString('base64')),
(error) => console.error('Error:', error)
);
Decrypt Data
This feature allows you to decrypt data that was encrypted using a KMS key. The code sample demonstrates how to decrypt a base64-encoded ciphertext.
const { KMSClient, DecryptCommand } = require('@aws-sdk/client-kms');
const client = new KMSClient({ region: 'us-west-2' });
const command = new DecryptCommand({
CiphertextBlob: Buffer.from('your-encrypted-data', 'base64')
});
client.send(command).then(
(data) => console.log('Decrypted Data:', data.Plaintext.toString()),
(error) => console.error('Error:', error)
);
Generate Data Key
This feature allows you to generate a data key that you can use to encrypt data locally. The code sample demonstrates how to generate a 256-bit AES data key.
const { KMSClient, GenerateDataKeyCommand } = require('@aws-sdk/client-kms');
const client = new KMSClient({ region: 'us-west-2' });
const command = new GenerateDataKeyCommand({
KeyId: 'your-key-id',
KeySpec: 'AES_256'
});
client.send(command).then(
(data) => console.log('Data Key:', data.Plaintext.toString('base64')),
(error) => console.error('Error:', error)
);
node-forge is a JavaScript library that provides a native implementation of various cryptographic functions, including key generation, encryption, and decryption. Unlike @aws-sdk/client-kms, node-forge does not integrate with AWS services and is used for local cryptographic operations.
crypto-js is a JavaScript library that provides a variety of cryptographic algorithms for encryption, decryption, hashing, and more. Similar to node-forge, it does not integrate with AWS services and is used for local cryptographic operations.
aws-sdk is the older version of the AWS SDK for JavaScript, which includes support for KMS among many other AWS services. It is a more comprehensive package compared to @aws-sdk/client-kms, which is part of the modular v3 SDK.
AWS SDK for JavaScript KMS Client for Node.js, Browser and React Native.
Key Management Service
Key Management Service (KMS) is an encryption and key management web service. This guide describes the KMS operations that you can call programmatically. For general information about KMS, see the Key Management Service Developer Guide .
KMS has replaced the term customer master key (CMK) with KMS key and KMS key. The concept has not changed. To prevent breaking changes, KMS is keeping some variations of this term.
Amazon Web Services provides SDKs that consist of libraries and sample code for various programming languages and platforms (Java, Ruby, .Net, macOS, Android, etc.). The SDKs provide a convenient way to create programmatic access to KMS and other Amazon Web Services services. For example, the SDKs take care of tasks such as signing requests (see below), managing errors, and retrying requests automatically. For more information about the Amazon Web Services SDKs, including how to download and install them, see Tools for Amazon Web Services.
We recommend that you use the Amazon Web Services SDKs to make programmatic API calls to KMS.
If you need to use FIPS 140-2 validated cryptographic modules when communicating with Amazon Web Services, use the FIPS endpoint in your preferred Amazon Web Services Region. For more information about the available FIPS endpoints, see Service endpoints in the Key Management Service topic of the Amazon Web Services General Reference.
All KMS API calls must be signed and be transmitted using Transport Layer Security (TLS). KMS recommends you always use the latest supported TLS version. Clients must also support cipher suites with Perfect Forward Secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve Ephemeral Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support these modes.
Signing Requests
Requests must be signed using an access key ID and a secret access key. We strongly recommend that you do not use your Amazon Web Services account root access key ID and secret access key for everyday work. You can use the access key ID and secret access key for an IAM user or you can use the Security Token Service (STS) to generate temporary security credentials and use those to sign requests.
All KMS requests must be signed with Signature Version 4.
Logging API Requests
KMS supports CloudTrail, a service that logs Amazon Web Services API calls and related events for your Amazon Web Services account and delivers them to an Amazon S3 bucket that you specify. By using the information collected by CloudTrail, you can determine what requests were made to KMS, who made the request, when it was made, and so on. To learn more about CloudTrail, including how to turn it on and find your log files, see the CloudTrail User Guide.
Additional Resources
For more information about credentials and request signing, see the following:
Amazon Web Services Security Credentials - This topic provides general information about the types of credentials used to access Amazon Web Services.
Temporary Security Credentials - This section of the IAM User Guide describes how to create and use temporary security credentials.
Signature Version 4 Signing Process - This set of topics walks you through the process of signing a request using an access key ID and a secret access key.
Commonly Used API Operations
Of the API operations discussed in this guide, the following will prove the most useful for most applications. You will likely perform operations other than these, such as creating keys and assigning policies, by using the console.
To install the this package, simply type add or install @aws-sdk/client-kms using your favorite package manager:
npm install @aws-sdk/client-kms
yarn add @aws-sdk/client-kms
pnpm add @aws-sdk/client-kms
The AWS SDK is modulized by clients and commands.
To send a request, you only need to import the KMSClient
and
the commands you need, for example ListAliasesCommand
:
// ES5 example
const { KMSClient, ListAliasesCommand } = require("@aws-sdk/client-kms");
// ES6+ example
import { KMSClient, ListAliasesCommand } from "@aws-sdk/client-kms";
To send a request, you:
send
operation on client with command object as input.destroy()
to close open connections.// a client can be shared by different commands.
const client = new KMSClient({ region: "REGION" });
const params = {
/** input parameters */
};
const command = new ListAliasesCommand(params);
We recommend using await operator to wait for the promise returned by send operation as follows:
// async/await.
try {
const data = await client.send(command);
// process data.
} catch (error) {
// error handling.
} finally {
// finally.
}
Async-await is clean, concise, intuitive, easy to debug and has better error handling as compared to using Promise chains or callbacks.
You can also use Promise chaining to execute send operation.
client.send(command).then(
(data) => {
// process data.
},
(error) => {
// error handling.
}
);
Promises can also be called using .catch()
and .finally()
as follows:
client
.send(command)
.then((data) => {
// process data.
})
.catch((error) => {
// error handling.
})
.finally(() => {
// finally.
});
We do not recommend using callbacks because of callback hell, but they are supported by the send operation.
// callbacks.
client.send(command, (err, data) => {
// process err and data.
});
The client can also send requests using v2 compatible style. However, it results in a bigger bundle size and may be dropped in next major version. More details in the blog post on modular packages in AWS SDK for JavaScript
import * as AWS from "@aws-sdk/client-kms";
const client = new AWS.KMS({ region: "REGION" });
// async/await.
try {
const data = await client.listAliases(params);
// process data.
} catch (error) {
// error handling.
}
// Promises.
client
.listAliases(params)
.then((data) => {
// process data.
})
.catch((error) => {
// error handling.
});
// callbacks.
client.listAliases(params, (err, data) => {
// process err and data.
});
When the service returns an exception, the error will include the exception information, as well as response metadata (e.g. request id).
try {
const data = await client.send(command);
// process data.
} catch (error) {
const { requestId, cfId, extendedRequestId } = error.$metadata;
console.log({ requestId, cfId, extendedRequestId });
/**
* The keys within exceptions are also parsed.
* You can access them by specifying exception names:
* if (error.name === 'SomeServiceException') {
* const value = error.specialKeyInException;
* }
*/
}
Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests, but have limited bandwidth to address them.
aws-sdk-js
on AWS Developer Blog.aws-sdk-js
.To test your universal JavaScript code in Node.js, browser and react-native environments, visit our code samples repo.
This client code is generated automatically. Any modifications will be overwritten the next time the @aws-sdk/client-kms
package is updated.
To contribute to client you can check our generate clients scripts.
This SDK is distributed under the Apache License, Version 2.0, see LICENSE for more information.
3.582.0 (2024-05-22)
FAQs
AWS SDK for JavaScript Kms Client for Node.js, Browser and React Native
The npm package @aws-sdk/client-kms receives a total of 966,836 weekly downloads. As such, @aws-sdk/client-kms popularity was classified as popular.
We found that @aws-sdk/client-kms demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PyPI now supports digital attestations, enhancing security and trust by allowing package maintainers to verify the authenticity of Python packages.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.