Code examples for Amazon KMS using Amazon SDKs - Amazon Key Management Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Code examples for Amazon KMS using Amazon SDKs

The following code examples show how to use Amazon KMS with an Amazon software development kit (SDK).

Basics are code examples that show you how to perform the essential operations within a service.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios.

Scenarios are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other Amazon Web Services services.

For a complete list of Amazon SDK developer guides and code examples, see Using Amazon KMS with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.

Get started

The following code example shows how to get started using KMS key.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsAsyncClient; import software.amazon.awssdk.services.kms.model.ListKeysRequest; import software.amazon.awssdk.services.kms.paginators.ListKeysPublisher; import java.util.concurrent.CompletableFuture; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class HelloKMS { public static void main(String[] args) { listAllKeys(); } public static void listAllKeys() { Region region = Region.US_WEST_2; KmsAsyncClient kmsAsyncClient = KmsAsyncClient.builder() .region(region) .build(); ListKeysRequest listKeysRequest = ListKeysRequest.builder() .limit(15) .build(); ListKeysPublisher keysPublisher = kmsAsyncClient.listKeysPaginator(listKeysRequest); CompletableFuture<Void> future = keysPublisher .subscribe(r -> r.keys().forEach(key -> System.out.println("The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId()))) .whenComplete((result, exception) -> { if (exception != null) { System.err.println("Error occurred: " + exception.getMessage()); } else { System.out.println("Successfully listed all keys."); } }); // Wait for the asynchronous operation to complete try { future.join(); } catch (Exception e) { System.err.println("Failed to list keys: " + e.getMessage()); } } }