Code examples for AWS KMS using AWS SDKs - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

Code examples for AWS KMS using AWS SDKs

The following code examples show you how to use AWS Key Management Service (AWS KMS) with an AWS software development kit (SDK).

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 and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

More resources

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 AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.ListKeysRequest; import software.amazon.awssdk.services.kms.model.KmsException; import software.amazon.awssdk.services.kms.paginators.ListKeysIterable; /** * 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) { Region region = Region.US_WEST_2; KmsClient kmsClient = KmsClient.builder() .region(region) .build(); listAllKeys(kmsClient); kmsClient.close(); } public static void listAllKeys(KmsClient kmsClient) { try { ListKeysRequest listKeysRequest = ListKeysRequest.builder() .limit(15) .build(); ListKeysIterable keysResponse = kmsClient.listKeysPaginator(listKeysRequest); keysResponse.stream() .flatMap(r -> r.keys().stream()) .forEach(key -> System.out .println(" The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId())); } catch (KmsException e) { System.err.println(e.getMessage()); System.exit(1); } } }