Skip to content

generate_mac

generate_mac(
    message: PlaintextType,
    key_id: KeyIdType,
    mac_algorithm: MacAlgorithmSpec,
    *,
    config_overrides: Optional[KMSClientConfig] = None,
    grant_tokens: Optional[GrantTokenList] = None,
    dry_run: Optional[NullableBooleanType] = None,
) -> GenerateMacResponse

Generates a hash-based message authentication code (HMAC) for a message using an HMAC KMS key and a MAC algorithm that the key supports. HMAC KMS keys and the HMAC algorithms that KMS uses conform to industry standards defined in RFC 2104.

You can use value that GenerateMac returns in the VerifyMac operation to demonstrate that the original message has not changed. Also, because a secret key is used to create the hash, you can verify that the party that generated the hash has the required secret key. You can also use the raw result to implement HMAC-based algorithms such as key derivation functions. This operation is part of KMS support for HMAC KMS keys. For details, see HMAC keys in KMS in the Key Management Service Developer Guide .

Best practices recommend that you limit the time during which any signing mechanism, including an HMAC, is effective. This deters an attack where the actor uses a signed message to establish validity repeatedly or long after the message is superseded. HMAC tags do not include a timestamp, but you can include a timestamp in the token or message to help you detect when its time to refresh the HMAC.

The KMS key that you use for this operation must be in a compatible key state. For details, see Key states of KMS keys in the Key Management Service Developer Guide.

Cross-account use: Yes. To perform this operation with a KMS key in a different Amazon Web Services account, specify the key ARN or alias ARN in the value of the KeyId parameter.

Required permissions: kms:GenerateMac (key policy)

Related operations: VerifyMac

Eventual consistency: The KMS API follows an eventual consistency model. For more information, see KMS eventual consistency.

Parameters:

  • message (PlaintextType) –

    The message to be hashed. Specify a message of up to 4,096 bytes.

    GenerateMac and VerifyMac do not provide special handling for message digests. If you generate an HMAC for a hash digest of a message, you must verify the HMAC of the same hash digest.

  • key_id (KeyIdType) –

    The HMAC KMS key to use in the operation. The MAC algorithm computes the HMAC for the message and the key as described in RFC 2104.

    To identify an HMAC KMS key, use the DescribeKey operation and see the KeySpec field in the response.

  • mac_algorithm (MacAlgorithmSpec) –

    The MAC algorithm used in the operation.

    The algorithm must be compatible with the HMAC KMS key that you specify. To find the MAC algorithms that your HMAC KMS key supports, use the DescribeKey operation and see the MacAlgorithms field in the DescribeKey response.

  • grant_tokens (Optional[GrantTokenList], default: None ) –

    A list of grant tokens.

    Use a grant token when your permission to call this operation comes from a new grant that has not yet achieved eventual consistency. For more information, see Grant token and Using a grant token in the Key Management Service Developer Guide.

  • dry_run (Optional[NullableBooleanType], default: None ) –

    Checks if your request will succeed. DryRun is an optional parameter.

    To learn more about how to use this parameter, see Testing your permissions in the Key Management Service Developer Guide.

Raises:

  • DisabledException –

    The request was rejected because the specified KMS key is not enabled.

  • DryRunOperationException –

    The request was rejected because the DryRun parameter was specified.

  • InvalidGrantTokenException –

    The request was rejected because the specified grant token is not valid.

  • InvalidKeyUsageException –

    The request was rejected for one of the following reasons:

    • The KeyUsage value of the KMS key is incompatible with the API operation.

    • The encryption algorithm or signing algorithm specified for the operation is incompatible with the type of key material in the KMS key (KeySpec).

    For encrypting, decrypting, re-encrypting, and generating data keys, the KeyUsage must be ENCRYPT_DECRYPT. For signing and verifying messages, the KeyUsage must be SIGN_VERIFY. For generating and verifying message authentication codes (MACs), the KeyUsage must be GENERATE_VERIFY_MAC. For deriving key agreement secrets, the KeyUsage must be KEY_AGREEMENT. To find the KeyUsage of a KMS key, use the DescribeKey operation.

    To find the encryption or signing algorithms supported for a particular KMS key, use the DescribeKey operation.

  • KeyUnavailableException –

    The request was rejected because the specified KMS key was not available. You can retry the request.

  • KMSInternalException –

    The request was rejected because an internal exception occurred. The request can be retried.

  • KMSInvalidStateException –

    The request was rejected because the state of the specified resource is not valid for this request.

    This exceptions means one of the following:

    • The key state of the KMS key is not compatible with the operation.

      To find the key state, use the DescribeKey operation. For more information about which key states are compatible with each KMS operation, see Key states of KMS keys in the Key Management Service Developer Guide .

    • For cryptographic operations on KMS keys in custom key stores, this exception represents a general failure with many possible causes. To identify the cause, see the error message that accompanies the exception.

  • NotFoundException –

    The request was rejected because the specified entity or resource could not be found.

  • UnknownServiceError –

    The service returned an error code this client does not model.

Examples:

To generate an HMAC for a message This example generates an HMAC for a message, an HMAC KMS key, and a MAC algorithm. The algorithm must be supported by the specified HMAC KMS key.

>>> client.generate_mac(message='Hello World', key_id='1234abcd-12ab-34cd-56ef-1234567890ab', mac_algorithm='HMAC_SHA_384')
Source code in docs_src/capo_kms/_services/kms.py
def generate_mac(
    self,
    message: "capo_kms.types.plaintext_type.PlaintextType",
    key_id: "capo_kms.types.key_id_type.KeyIdType",
    mac_algorithm: "capo_kms.types.mac_algorithm_spec.MacAlgorithmSpec",
    *,
    config_overrides: Optional[KMSClientConfig] = None,
    grant_tokens: Optional["capo_kms.types.grant_token_list.GrantTokenList"] = None,
    dry_run: Optional[
        "capo_kms.types.nullable_boolean_type.NullableBooleanType"
    ] = None,
) -> "capo_kms.types.generate_mac_response.GenerateMacResponse":
    """<p>Generates a hash-based message authentication code (HMAC) for a message using an HMAC KMS key and a MAC algorithm that the key supports. HMAC KMS keys and the HMAC algorithms that KMS uses conform to industry standards defined in <a href="https://datatracker.ietf.org/doc/html/rfc2104">RFC 2104</a>.</p> <p>You can use value that GenerateMac returns in the <a>VerifyMac</a> operation to demonstrate that the original message has not changed. Also, because a secret key is used to create the hash, you can verify that the party that generated the hash has the required secret key. You can also use the raw result to implement HMAC-based algorithms such as key derivation functions. This operation is part of KMS support for HMAC KMS keys. For details, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/hmac.html">HMAC keys in KMS</a> in the <i> <i>Key Management Service Developer Guide</i> </i>.</p> <note> <p>Best practices recommend that you limit the time during which any signing mechanism, including an HMAC, is effective. This deters an attack where the actor uses a signed message to establish validity repeatedly or long after the message is superseded. HMAC tags do not include a timestamp, but you can include a timestamp in the token or message to help you detect when its time to refresh the HMAC. </p> </note> <p>The KMS key that you use for this operation must be in a compatible key state. For details, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key states of KMS keys</a> in the <i>Key Management Service Developer Guide</i>.</p> <p> <b>Cross-account use</b>: Yes. To perform this operation with a KMS key in a different Amazon Web Services account, specify the key ARN or alias ARN in the value of the <code>KeyId</code> parameter. </p> <p> <b>Required permissions</b>: <a href="https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html">kms:GenerateMac</a> (key policy)</p> <p> <b>Related operations</b>: <a>VerifyMac</a> </p> <p> <b>Eventual consistency</b>: The KMS API follows an eventual consistency model. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/accessing-kms.html#programming-eventual-consistency">KMS eventual consistency</a>.</p>

    Args:
        message: <p>The message to be hashed. Specify a message of up to 4,096 bytes. </p> <p> <code>GenerateMac</code> and <a>VerifyMac</a> do not provide special handling for message digests. If you generate an HMAC for a hash digest of a message, you must verify the HMAC of the same hash digest.</p>
        key_id: <p>The HMAC KMS key to use in the operation. The MAC algorithm computes the HMAC for the message and the key as described in <a href="https://datatracker.ietf.org/doc/html/rfc2104">RFC 2104</a>.</p> <p>To identify an HMAC KMS key, use the <a>DescribeKey</a> operation and see the <code>KeySpec</code> field in the response.</p>
        mac_algorithm: <p>The MAC algorithm used in the operation.</p> <p> The algorithm must be compatible with the HMAC KMS key that you specify. To find the MAC algorithms that your HMAC KMS key supports, use the <a>DescribeKey</a> operation and see the <code>MacAlgorithms</code> field in the <code>DescribeKey</code> response.</p>
        grant_tokens: <p>A list of grant tokens.</p> <p>Use a grant token when your permission to call this operation comes from a new grant that has not yet achieved <i>eventual consistency</i>. For more information, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/grants.html#grant_token">Grant token</a> and <a href="https://docs.aws.amazon.com/kms/latest/developerguide/using-grant-token.html">Using a grant token</a> in the <i>Key Management Service Developer Guide</i>.</p>
        dry_run: <p>Checks if your request will succeed. <code>DryRun</code> is an optional parameter. </p> <p>To learn more about how to use this parameter, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/testing-permissions.html">Testing your permissions</a> in the <i>Key Management Service Developer Guide</i>.</p>

    Raises:
        capo_kms.errors.disabled_exception.DisabledException: <p>The request was rejected because the specified KMS key is not enabled.</p>
        capo_kms.errors.dry_run_operation_exception.DryRunOperationException: <p> The request was rejected because the DryRun parameter was specified. </p>
        capo_kms.errors.invalid_grant_token_exception.InvalidGrantTokenException: <p>The request was rejected because the specified grant token is not valid.</p>
        capo_kms.errors.invalid_key_usage_exception.InvalidKeyUsageException: <p>The request was rejected for one of the following reasons: </p> <ul> <li> <p>The <code>KeyUsage</code> value of the KMS key is incompatible with the API operation.</p> </li> <li> <p>The encryption algorithm or signing algorithm specified for the operation is incompatible with the type of key material in the KMS key <code>(KeySpec</code>).</p> </li> </ul> <p>For encrypting, decrypting, re-encrypting, and generating data keys, the <code>KeyUsage</code> must be <code>ENCRYPT_DECRYPT</code>. For signing and verifying messages, the <code>KeyUsage</code> must be <code>SIGN_VERIFY</code>. For generating and verifying message authentication codes (MACs), the <code>KeyUsage</code> must be <code>GENERATE_VERIFY_MAC</code>. For deriving key agreement secrets, the <code>KeyUsage</code> must be <code>KEY_AGREEMENT</code>. To find the <code>KeyUsage</code> of a KMS key, use the <a>DescribeKey</a> operation.</p> <p>To find the encryption or signing algorithms supported for a particular KMS key, use the <a>DescribeKey</a> operation.</p>
        capo_kms.errors.key_unavailable_exception.KeyUnavailableException: <p>The request was rejected because the specified KMS key was not available. You can retry the request.</p>
        capo_kms.errors.kms_internal_exception.KMSInternalException: <p>The request was rejected because an internal exception occurred. The request can be retried.</p>
        capo_kms.errors.kms_invalid_state_exception.KMSInvalidStateException: <p>The request was rejected because the state of the specified resource is not valid for this request.</p> <p>This exceptions means one of the following:</p> <ul> <li> <p>The key state of the KMS key is not compatible with the operation. </p> <p>To find the key state, use the <a>DescribeKey</a> operation. For more information about which key states are compatible with each KMS operation, see <a href="https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">Key states of KMS keys</a> in the <i> <i>Key Management Service Developer Guide</i> </i>.</p> </li> <li> <p>For cryptographic operations on KMS keys in custom key stores, this exception represents a general failure with many possible causes. To identify the cause, see the error message that accompanies the exception.</p> </li> </ul>
        capo_kms.errors.not_found_exception.NotFoundException: <p>The request was rejected because the specified entity or resource could not be found.</p>
        capo_kms.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        To generate an HMAC for a message
        This example generates an HMAC for a message, an HMAC KMS key, and a MAC algorithm. The algorithm must be supported by the specified HMAC KMS key.

        >>> client.generate_mac(message='Hello World', key_id='1234abcd-12ab-34cd-56ef-1234567890ab', mac_algorithm='HMAC_SHA_384')
    """

    def _handler(
        req: "OperationRequest[capo_kms.types.generate_mac_request.GenerateMacRequest]",
    ) -> OperationResponse[
        "capo_kms.types.generate_mac_response.GenerateMacResponse"
    ]:
        import capo_kms._operations.trent_service.generate_mac

        output, http_response = (
            capo_kms._operations.trent_service.generate_mac.generate_mac(
                req.options, req.input
            )
        )
        return OperationResponse(output=output, response=http_response)

    def _redact_input(
        input_: "capo_kms.types.generate_mac_request.GenerateMacRequest",
    ) -> dict[str, Any]:
        import capo_kms.types.generate_mac_request

        return capo_kms.types.generate_mac_request.redact_sensitive(input_)

    interceptors_, options_ = self.operation_options(
        config_overrides,
        OperationLogging("GenerateMac", redact_input=_redact_input),
    )
    input_: capo_kms.types.generate_mac_request.GenerateMacRequest = {
        "message": message,
        "key_id": key_id,
        "mac_algorithm": mac_algorithm,
    }
    if grant_tokens is not None:
        input_["grant_tokens"] = grant_tokens
    if dry_run is not None:
        input_["dry_run"] = dry_run

    response = execute_pipeline(
        OperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    response.response.close()
    return response.output