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 with an AWS 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 AWS services.
Get started
The following code example shows how to get started using KMS key.
- Java
-
- SDK for Java 2.x
-
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());
}
}
}