Sign与 Amazon SDK 或 CLI 配合使用 - Amazon Key Management Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Sign与 Amazon SDK 或 CLI 配合使用

以下代码示例演示如何使用 Sign

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

CLI
Amazon CLI

示例 1:为消息生成数字签名

以下 sign 示例为一条短消息生成加密签名。该命令的输出包括一个 base-64 编码的 Signature 字段,您可以使用 verify 命令对其进行验证。

您必须指定要签名的消息以及您的非对称 KMS 密钥支持的签名算法。要获取 KMS 密钥的签名算法,请使用 describe-key 命令。

在 Amazon CLI 2.0 中,message参数的值必须采用 Base64 编码。或者,您可以将消息保存在文件中并使用fileb://前缀,因为它指示 Amazon CLI 从文件中读取二进制数据。

在运行此命令之前,请将密钥 ID 示例替换为您 Amazon 账户中的有效密钥 ID。密钥 ID 必须表示密钥用法为 SIGN_VERIFY 的非对称 KMS 密钥。

msg=(echo 'Hello World' | base64) aws kms sign \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --message fileb://UnsignedMessage \ --message-type RAW \ --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256

输出:

{ "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "Signature": "ABCDEFhpyVYyTxbafE74ccSvEJLJr3zuoV1Hfymz4qv+/fxmxNLA7SE1SiF8lHw80fKZZ3bJ...", "SigningAlgorithm": "RSASSA_PKCS1_V1_5_SHA_256" }

有关在 Amazon KMS 中使用非对称 KMS 密钥的更多信息,请参阅《密钥管理服务开发人员指南》中的 Amazon KMS 中的非对称Amazon钥。

示例 2:将数字签名保存在文件中(Linux 和 macOS)

以下 sign 示例为一条存储在本地文件中的短消息生成加密签名。该命令还从响应中获取Signature属性,对其进行 Base64 解码并将其保存到文件中。 ExampleSignature 您可以在验证签名的 verify 命令中使用该签名文件。

sign 命令需要一条 Base64 编码的消息和您的非对称 KMS 密钥支持的签名算法。要获取 KMS 密钥支持的签名算法,请使用 describe-key 命令。

在运行此命令之前,请将密钥 ID 示例替换为您 Amazon 账户中的有效密钥 ID。密钥 ID 必须表示密钥用法为 SIGN_VERIFY 的非对称 KMS 密钥。

echo 'hello world' | base64 > EncodedMessage aws kms sign \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --message fileb://EncodedMessage \ --message-type RAW \ --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256 \ --output text \ --query Signature | base64 --decode > ExampleSignature

此命令不生成任何输出。此示例提取输出的 Signature 属性并将其保存在文件中。

有关在 Amazon KMS 中使用非对称 KMS 密钥的更多信息,请参阅《密钥管理服务开发人员指南》中的 Amazon KMS 中的非对称Amazon钥。

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 Sign

Java
适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/** * Asynchronously signs and verifies data using AWS KMS. * * <p>The method performs the following steps: * <ol> * <li>Creates an AWS KMS key with the specified key spec, key usage, and origin.</li> * <li>Signs the provided message using the created KMS key and the RSASSA-PSS-SHA-256 algorithm.</li> * <li>Verifies the signature of the message using the created KMS key and the RSASSA-PSS-SHA-256 algorithm.</li> * </ol> * * @return a {@link CompletableFuture} that completes with the result of the signature verification, * {@code true} if the signature is valid, {@code false} otherwise. * @throws KmsException if any error occurs during the KMS operations. * @throws RuntimeException if an unexpected error occurs. */ public CompletableFuture<Boolean> signVerifyDataAsync() { String signMessage = "Here is the message that will be digitally signed"; // Create an AWS KMS key used to digitally sign data. CreateKeyRequest createKeyRequest = CreateKeyRequest.builder() .keySpec(KeySpec.RSA_2048) .keyUsage(KeyUsageType.SIGN_VERIFY) .origin(OriginType.AWS_KMS) .build(); return getAsyncClient().createKey(createKeyRequest) .thenCompose(createKeyResponse -> { String keyId = createKeyResponse.keyMetadata().keyId(); SdkBytes messageBytes = SdkBytes.fromString(signMessage, Charset.defaultCharset()); SignRequest signRequest = SignRequest.builder() .keyId(keyId) .message(messageBytes) .signingAlgorithm(SigningAlgorithmSpec.RSASSA_PSS_SHA_256) .build(); return getAsyncClient().sign(signRequest) .thenCompose(signResponse -> { byte[] signedBytes = signResponse.signature().asByteArray(); VerifyRequest verifyRequest = VerifyRequest.builder() .keyId(keyId) .message(SdkBytes.fromByteArray(signMessage.getBytes(Charset.defaultCharset()))) .signature(SdkBytes.fromByteBuffer(ByteBuffer.wrap(signedBytes))) .signingAlgorithm(SigningAlgorithmSpec.RSASSA_PSS_SHA_256) .build(); return getAsyncClient().verify(verifyRequest) .thenApply(verifyResponse -> { return (boolean) verifyResponse.signatureValid(); }); }); }) .exceptionally(throwable -> { throw new RuntimeException("Failed to sign or verify data", throwable); }); }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Sign

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/*** * @param string $keyId * @param string $message * @param string $algorithm * @return Result */ public function sign(string $keyId, string $message, string $algorithm) { try { return $this->client->sign([ 'KeyId' => $keyId, 'Message' => $message, 'SigningAlgorithm' => $algorithm, ]); }catch(KmsException $caught){ echo "There was a problem signing the data: {$caught->getAwsErrorMessage()}\n"; throw $caught; } }
  • 有关 API 详细信息,请参阅《适用于 PHP 的 Amazon SDK API 参考》中的 Sign

Python
适用于 Python 的 SDK(Boto3)
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

class KeyEncrypt: def __init__(self, kms_client): self.kms_client = kms_client @classmethod def from_client(cls) -> "KeyEncrypt": """ Creates a KeyEncrypt instance with a default KMS client. :return: An instance of KeyEncrypt initialized with the default KMS client. """ kms_client = boto3.client("kms") return cls(kms_client) def sign(self, key_id: str, message: str) -> str: """ Signs a message with a key. :param key_id: The ARN or ID of the key to use for signing. :param message: The message to sign. :return: The signature of the message. """ try: return self.kms_client.sign( KeyId=key_id, Message=message.encode(), SigningAlgorithm="RSASSA_PSS_SHA_256", )["Signature"] except ClientError as err: logger.error( "Couldn't sign your message. Here's why: %s", err.response["Error"]["Message"], ) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 Sign

有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅将此服务与 Amazon SDK 配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。