本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
AWS KMS 使用 的程式碼範例 AWS SDKs
下列程式碼範例示範如何使用 AWS 軟體開發套件 AWS KMS (SDK)。
基本知識是程式碼範例,示範如何在 服務中執行基本操作。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。
如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 將此服務與 搭配使用 AWS SDK。本主題也包含有關入門的資訊,以及先前SDK版本的詳細資訊。
開始使用
下列程式碼範例示範如何開始使用 AWS Key Management Service。
- Java
-
- SDK 適用於 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());
}
}
}
- PHP
-
- 適用於 PHP 的 SDK
-
include "vendor/autoload.php";
use Aws\Kms\KmsClient;
echo "This file shows how to connect to the KmsClient, uses a paginator to get the keys for the account, and lists the KeyIds for up to 10 keys.\n";
$client = new KmsClient([]);
$pageLength = 10; // Change this value to change the number of records shown, or to break up the result into pages.
$keys = [];
$keysPaginator = $client->getPaginator("ListKeys", ['Limit' => $pageLength]);
foreach($keysPaginator as $page){
foreach($page['Keys'] as $index => $key){
echo "The $index index Key's ID is: {$key['KeyId']}\n";
}
echo "End of page one of results. Alter the \$pageLength variable to see more results.\n";
break;
}