Keymaster Functions

This page provides details to assist implementers of Keymaster Hardware Abstraction Layers (HALs). It covers each function in the API and which Keymaster version that function is available in and describes the default implementation. For tags, see the Keymaster Tags page.

To support Keymaster 3's transition from the old-style C-structure HAL to the C++ HAL interface generated from a definition in the new Hardware Interface Definition Language (HIDL), function names have changed in Android 8.0. To support this, functions are now in camel case. For example, get_key_characteristics is now getKeyCharacteristics.

General implementation guidelines

The following guidelines apply to all functions in the API.

Input pointer parameters

Version: 1, 2

Input pointer parameters that are not used for a given call may be NULL. The caller is not required to provide placeholders. For example, some key types and modes may not use any values from the inParams argument to begin, so the caller may set inParams to NULL or provide an empty parameter set. Callers can also provide unused parameters, and Keymaster methods should not issue errors.

If a required input parameter is NULL, Keymaster methods should return ErrorCode::UNEXPECTED_NULL_POINTER.

Starting in Keymaster 3, there are no pointer parameters. All parameters are passed by value or const references.

Output pointer parameters

Version: 1, 2

Similar to input pointer parameters, unused output pointer parameters may be NULL. If a method needs to return data in an output parameter found to be NULL, it should return ErrorCode::OUTPUT_PARAMETER_NULL.

Starting in Keymaster 3, there are no pointer parameters. All parameters are passed by value or const references.

API misuse

Version: 1, 2, 3

There are many ways that callers can make requests that don't make sense or are foolish but not technically wrong. Keymaster implementations are not required to fail in such cases or issue a diagnostic. Use of too-small keys, specification of irrelevant input parameters, reuse of IVs or nonces, generation of keys with no purposes (hence useless) and the like should not be diagnosed by implementations. Omission of required parameters, specification of invalid required parameters, and similar errors must be diagnosed.

It is the responsibility of apps, the framework, and Android keystore to ensure that the calls to Keymaster modules are sensible and useful.

Keymaster implementations should attempt to diagnose serious errors, such as omission of required parameters, specification of invalid required parameters, and similar errors that compromise the integrity of the Keymaster implementation.

Functions

getHardwareFeatures

Version: 3

The new getHardwareFeatures method exposes to clients some important characteristics of the underlying secure hardware. The method takes no arguments and returns four values, all booleans:

  • isSecure is true if keys are stored in secure hardware (TEE, etc.) and never leave it.
  • supportsEllipticCurve is true if the hardware supports Elliptic Curve cryptography with the NIST curves (P-224, P-256, P-384, and P-521).
  • supportsSymmetricCryptography is true if the hardware supports symmetric cryptography, including AES and HMAC.
  • supportsAttestation is true if the hardware supports generation of Keymaster public key attestation certificates, signed with a key injected in a secure environment.

The only error codes this method may return are ErrorCode:OK, ErrorCode::KEYMASTER_NOT_CONFIGURED or one of the error codes indicating a failure to communicate with the secure hardware.

getHardwareFeatures()
    generates(bool isSecure, bool supportsEllipticCurve, bool supportsSymmetricCryptography,
              bool supportsAttestation, bool supportsAllDigests, string keymasterName,
              string keymasterAuthorName);

configure

Version: 2

This function was introduced in Keymaster 2 and deprecated in Keymaster 3, as this information is available in system properties files, and manufacturer implementations read those files during startup.

Configures keymaster. This method is called once after the device is opened and before it is used. It's used to provide KM_TAG_OS_VERSION and KM_TAG_OS_PATCHLEVEL to keymaster. Until this method is called, all other methods return KM_ERROR_KEYMASTER_NOT_CONFIGURED. The values provided by this method are only accepted by keymaster once per boot. Subsequent calls return KM_ERROR_OK, but do nothing.

If the keymaster implementation is in secure hardware and the OS version and patch level values provided do not match the values provided to the secure hardware by the bootloader (or if the bootloader did not provide values), then this method returns KM_ERROR_INVALID_ARGUMENT, and all other methods continue returning KM_ERROR_KEYMASTER_NOT_CONFIGURED.

keymaster_error_t (*configure)(const struct keymaster2_device* dev,
                               const keymaster_key_param_set_t* params);

addRngEntropy

Version: 1, 2, 3

This function was introduced in Keymaster 1 as add_rng_entropy and renamed in Keymaster 3.

Adds caller-provided entropy to the pool used by the Keymaster 1 implementation for generating random numbers, for keys, IVs, etc.

Keymaster implementations need to securely mix the provided entropy into their pool, which also must contain internally-generated entropy from a hardware random number generator. Mixing should be handled so that an attacker who has complete control of either the addRngEntropy-provided bits or the hardware-generated bits, but not both, has no non-neglible advantage in predicting the bits generated from the entropy pool.

Keymaster implementations that attempt to estimate the entropy in their internal pool assume that data provided by addRngEntropy contains no entropy. Keymaster implementations may return ErrorCode::INVALID_INPUT_LENGTH if they're given more than 2 KiB of data in a single call.

generateKey

Version: 1, 2, 3

This function was introduced in Keymaster 1 as generate_key and renamed in Keymaster 3.

Generates a new cryptographic key, specifying associated authorizations, which are permanently bound to the key. Keymaster implementations make it impossible to use a key in any way inconsistent with the authorizations specified at generation time. With respect to authorizations that the secure hardware cannot enforce, the secure hardware's obligation is limited to ensuring that the unenforceable authorizations associated with the key cannot be modified, so that every call to getKeyCharacteristics returns the original value. In addition, the characteristics returned by generateKey allocates authorizations correctly between the hardware-enforced and software-enforced lists. See getKeyCharacteristics for more details.

The parameters provided to generateKey depend on the type of key being generated. This section summarizes the necessary and optional tags for each type of key. Tag::ALGORITHM is always necessary, to specify the type.

RSA keys

The following parameters are necessary to generate an RSA key.

  • Tag::KEY_SIZE specifies the size of the public modulus, in bits. If omitted, the method returns ErrorCode::UNSUPPORTED_KEY_SIZE. Supported values are 1024, 2048, 3072 and 4096. Recommended values are all key sizes that are a multiple of 8.
  • Tag::RSA_PUBLIC_EXPONENT specifies the RSA public exponent value. If omitted, the method returns ErrorCode::INVALID_ARGUMENT. Supported values are 3 and 65537. Recommended values are all prime values up to 2^64.

The following parameters are not necessary to generate an RSA key, but creating an RSA key without them produces a key that is unusable. However, the generateKey function doesn't return an error if these parameters are omitted.

  • Tag::PURPOSE specifies allowed purposes. All purposes need to be supported for RSA keys, in any combination.
  • Tag::DIGEST specifies digest algorithms that may be used with the new key. Implementations that do not support all digest algorithms need to accept key generation requests that include unsupported digests. The unsupported digests should be placed in the "software-enforced" list in the returned key characteristics. This is because the key is usable with those other digests, but digesting is performed in software. Then hardware is called to perform the operation with Digest::NONE.
  • Tag::PADDING specifies the padding modes that may be used with the new key. Implementations that do not support all digest algorithms need to place PaddingMode::RSA_PSS and PaddingMode::RSA_OAEP in the software-enforced list of the key characteristics if any unsupported digest algorithms are specified.

ECDSA keys

Only Tag::KEY_SIZE is necessary to generate an ECDSA key. It is used to select the EC group. Supported values are 224, 256, 384 and 521, which indicate the NIST p-224, p-256, p-384 and p521 curves, respectively.

Tag::DIGEST is also necessary for a useful ECDSA key, but is not required for generation.

AES keys

Only Tag::KEY_SIZE is necessary to generate an AES key. If omitted, the method returns ErrorCode::UNSUPPORTED_KEY_SIZE. Supported values are 128 and 256, with optional support for 192-bit AES keys.

The following parameters are particularly relevant for AES keys, but not necessary to generate one:

  • Tag::BLOCK_MODE specifies the block modes with which the new key may be used.
  • Tag::PADDING specifies the padding modes that may be used. This is only relevant for ECB and CBC modes.

If the GCM block mode is specified, then provide the Tag::MIN_MAC_LENGTH. If omitted, the method returns ErrorCode::MISSING_MIN_MAC_LENGTH. The tag's value is a multiple of 8 and between 96 and 128.

HMAC keys

The following parameters are required for HMAC key generation:

  • Tag::KEY_SIZE specifies the key size in bits. Values smaller than 64 and values that are not multiples of 8 are not supported. All multiples of 8, from 64 to 512, are supported. Larger values may be supported.
  • Tag::MIN_MAC_LENGTH specifies the minimum length of MACs that can be generated or verified with this key. The value is a multiple of 8 and at least 64.
  • Tag::DIGEST specifies the digest algorithm for the key. Exactly one digest is specified, otherwise return ErrorCode::UNSUPPORTED_DIGEST. If the digest is not supported by the trustlet, return ErrorCode::UNSUPPORTED_DIGEST.

Key characteristics

If the characteristics argument is non-NULL, generateKey returns the newly-generated key's characteristics divided appropriately into hardware-enforced and software-enforced lists. See getKeyCharacteristics for a description of which characteristics go in which list. The returned characteristics include all of the parameters specified to key generation, except Tag::APPLICATION_ID and Tag::APPLICATION_DATA. If these tags were included in the key parameters, they are removed from the returned characteristics so that it is not be possible to find their values by examining the returned key blob. However, they are cryptographically bound to the key blob, so that if the correct values are not provided when the key is used, usage fails. Similarly, Tag::ROOT_OF_TRUST is cryptographically bound to the key, but it may not be specified during key creation or import and is never returned.

In addition to the provided tags, the trustlet also adds Tag::ORIGIN, with the value KeyOrigin::GENERATED, and if the key is rollback resistant, Tag::ROLLBACK_RESISTANT.

Rollback resistance

Rollback resistance means that once a key is deleted with deleteKey or deleteAllKeys, it is guaranteed by secure hardware never to be usable again. Implementations without rollback resistance typically return generated or imported key material to the caller as a key blob, an encrypted and authenticated form. When keystore deletes the key blob, the key is gone, but an attacker who has previously managed to retrieve the key material can potentially restore it to the device.

A key is rollback resistant if the secure hardware guarantees that deleted keys cannot be restored later. This is generally done by storing additional key metadata in a trusted location that cannot be manipulated by an attacker. On mobile devices, the mechanism used for this is usually Replay Protected Memory Blocks (RPMB). Because the number of keys that may be created is essentially unbounded and the trusted storage used for rollback resistance may be limited in size, this method needs to succeed even if rollback resistance cannot be provided for the new key. In that case, Tag::ROLLBACK_RESISTANT should not be added to the key characteristics.

getKeyCharacteristics

Version: 1, 2, 3

This function was introduced in Keymaster 1 as get_key_characteristics and renamed in Keymaster 3.

Returns parameters and authorizations associated with the provided key, divided into two sets: hardware-enforced and software-enforced. The description here applies equally to the key characteristics lists returned by generateKey and importKey.

If Tag::APPLICATION_ID was provided during key generation or import, the same value is provided to this method in the clientId argument. Otherwise, the method returns ErrorCode::INVALID_KEY_BLOB. Similarly, if Tag::APPLICATION_DATA was provided during generation or import, the same value is provided to this method in the appData argument.

The characteristics returned by this method completely describe the type and usage of the specified key.

The general rule for deciding whether a given tag belongs in the hardware-enforced or software-enforced list is that if the meaning of the tag is fully assured by secure hardware, it is hardware enforced. Otherwise, it's software enforced. Below is a list of specific tags whose correct allocation may be unclear:

  • Tag::ALGORITHM, Tag::KEY_SIZE, and Tag::RSA_PUBLIC_EXPONENT are intrinsic properties of the key. For any key that is secured by hardware, these tags will be in the hardware-enforced list.
  • Tag::DIGEST values that are supported by the secure hardware are placed in the hardware-supported list. Unsupported digests go in the software-supported list.
  • Tag::PADDING values generally go in the hardware-supported list, unlessthere is a possibility that a specific padding mode may have to be performed by software. In that case, they go in the software-enforced list. Such a possibility arises for RSA keys that permit PSS or OAEP padding with digest algorithms that are not supported by the secure hardware.
  • Tag::USER_SECURE_ID and Tag::USER_AUTH_TYPE are hardware-enforced only if user authentication is hardware enforced. To accomplish this, the Keymaster trustlet and the relevant authentication trustlet both have to be secure and share a secret HMAC key used to sign and validate authentication tokens. See the Authentication page for details.
  • Tag::ACTIVE_DATETIME, Tag::ORIGINATION_EXPIRE_DATETIME, and Tag::USAGE_EXPIRE_DATETIME tags require access to a verifiably correct wall clock. Most secure hardware only has access to time information provided by the non-secure OS, which means the tags are software enforced.
  • Tag::ORIGIN is always in the hardware list for hardware-bound keys. Its presence in that list is the way higher layers determine that a key is hardware-backed.

importKey

Version: 1, 2, 3

This function was introduced in Keymaster 1 as import_key and renamed in Keymaster 3.

Imports key material into Keymaster hardware. Key definition parameters and output characteristics are handled the same as for generateKey, with the following exceptions:

  • Tag::KEY_SIZE and Tag::RSA_PUBLIC_EXPONENT (for RSA keys only) are not necessary in the input parameters. If not provided, the trustlet deduces the values from the provided key material and adds appropriate tags and values to the key characteristics. If the parameters are provided, the trustlet validates them against the key material. In the event of a mismatch, the method returns ErrorCode::IMPORT_PARAMETER_MISMATCH.
  • The returned Tag::ORIGIN has the same value as KeyOrigin::IMPORTED.

exportKey

Version: 1, 2, 3

This function was introduced in Keymaster 1 as export_key and renamed in Keymaster 3.

Exports a public key from a Keymaster RSA or EC key pair.

If Tag::APPLICATION_ID was provided during key generation or import, the same value is provided to this method in the clientId argument. Otherwise, the method returns ErrorCode::INVALID_KEY_BLOB. Similarly, if Tag::APPLICATION_DATA was provided during generation or import, the same value is provided to this method in the appData argument.

deleteKey

Version: 1, 2, 3

This function was introduced in Keymaster 1 as delete_key and renamed in Keymaster 3.

Deletes the provided key. This method is optional, and is only implemented by Keymaster modules that provide rollback resistance.

deleteAllKeys

Version: 1, 2, 3

This function was introduced in Keymaster 1 as delete_all_keys and renamed in Keymaster 3.

Deletes all keys. This method is optional, and is only implemented by Keymaster modules that provide rollback resistance.

destroyAttestationIds

Version: 3

The destroyAttestationIds() method is used to permanently disable the new (optional, but highly recommended) ID attestation feature. If the TEE has no way to ensure that ID attestation is permanently disabled after this method is called, then ID attestation must not be implemented at all, in which case this method does nothing and returns ErrorCode::UNIMPLEMENTED. If ID attestation is supported, this method needs to be implemented and must permanently disable all future ID attestation attempts. The method may be called any number of times. If ID attestation is permanently disabled already, the method does nothing and returns ErrorCode::OK.

The only error codes this method may return are ErrorCode::UNIMPLEMENTED (if ID attestation is not supported), ErrorCode:OK, ErrorCode::KEYMASTER_NOT_CONFIGURED or one of the error codes indicating a failure to communicate with the secure hardware.

begin

Version: 1, 2, 3

Begins a cryptographic operation, using the specified key, for the specified purpose, with the specified parameters (as appropriate), and returns an operation handle that is used with update and finish to complete the operation. The operation handle is also used as the "challenge" token in authenticated operations, and for such operations is included in the challenge field of the authentication token.

A Keymaster implementation supports at least 16 concurrent operations. Keystore uses up to 15, leaving one for vold to use for password encryption. When Keystore has 15 operations in progress (begin has been called, but finish or abort have not yet been called) and it receives a request to begin a 16th, it calls abort on the least-recently used operation to reduce the number of active operations to 14 before calling begin to start the newly-requested operation.

If Tag::APPLICATION_ID or Tag::APPLICATION_DATA were specified during key generation or import, calls to begin include those tags with the originally-specified values in the inParams argument to this method.

Authorization enforcement

During this method, the following key authorizations are enforced by the trustlet if the implementation placed them in the "hardware-enforced" characteristics and if the operation is not a public key operation. Public key operations, meaning KeyPurpose::ENCRYPT and KeyPurpose::VERIFY, with RSA or EC keys, are allowed to succeed even if authorization requirements are not met.

  • Tag::PURPOSE: The purpose specified in the begin() call has to match one of the purposes in the key authorizations, unless the requested operation is a public key operation. If the specified purpose does not match and the operation is not a public key operation, begin will return ErrorCode::UNSUPPORTED_PURPOSE. Public key operations are asymmetric encryption or verification operations.
  • Tag::ACTIVE_DATETIME can only be enforced if a trusted UTC time source is available. If the current date and time is prior to the tag value, the method returns ErrorCode::KEY_NOT_YET_VALID.
  • Tag::ORIGINATION_EXPIRE_DATETIME can only be enforced if a trusted UTC time source is available. If the current date and time is later than the tag value and the purpose is KeyPurpose::ENCRYPT or KeyPurpose::SIGN, the method returns ErrorCode::KEY_EXPIRED.
  • Tag::USAGE_EXPIRE_DATETIME can only be enforced if a trusted UTC time source is available. If the current date and time is later than the tag value and the purpose is KeyPurpose::DECRYPT or KeyPurpose::VERIFY, the method returns ErrorCode::KEY_EXPIRED.
  • Tag::MIN_SECONDS_BETWEEN_OPS is compared with a trusted relative timer indicating the last use of the key. If the last use time plus the tag value is less than the current time, the method returns ErrorCode::KEY_RATE_LIMIT_EXCEEDED. See the tag description for important implementation details.
  • Tag::MAX_USES_PER_BOOT is compared against a secure counter that tracks the uses of the key since boot time. If the count of previous uses exceeds the tag value, the method returns ErrorCode::KEY_MAX_OPS_EXCEEDED.
  • Tag::USER_SECURE_ID is enforced by this method only if the key also has Tag::AUTH_TIMEOUT. If the key has both, then this method must receive a valid Tag::AUTH_TOKEN in inParams. For the auth token to be valid, all of the following has to be true:
    • The HMAC field validates correctly.
    • At least one of the Tag::USER_SECURE_ID values from the key matches at least one of the secure ID values in the token.
    • The key has a Tag::USER_AUTH_TYPE that matches the auth type in the token.

    If any of these conditions aren't met, the method returns ErrorCode::KEY_USER_NOT_AUTHENTICATED.

  • Tag::CALLER_NONCE allows the caller to specify a nonce or initialization vector (IV). If the key doesn't have this tag, but the caller provided Tag::NONCE to this method, ErrorCode::CALLER_NONCE_PROHIBITED is returned.
  • Tag::BOOTLOADER_ONLY specifies that only the bootloader may use the key. If this method is called with a bootloader-only key after the bootloader has finished executing, it returns ErrorCode::INVALID_KEY_BLOB.

RSA keys

All RSA key operations specify exactly one padding mode in inParams. If unspecified or specified more than once, the method returns ErrorCode::UNSUPPORTED_PADDING_MODE.

RSA signing and verification operations need a digest, as do RSA encryption and decryption operations with OAEP padding mode. For those cases, the caller specifies exactly one digest in inParams. If unspecified or specified more than once, the method returns ErrorCode::UNSUPPORTED_DIGEST.

Private key operations (KeyPurpose::DECYPT and KeyPurpose::SIGN) need authorization of digest and padding, which means that the key authorizations need to contain the specified values. If not, the method returns ErrorCode::INCOMPATIBLE_DIGEST or ErrorCode::INCOMPATIBLE_PADDING, as appropriate. Public key operations (KeyPurpose::ENCRYPT and KeyPurpose::VERIFY) are permitted with unauthorized digest or padding.

With the exception of PaddingMode::NONE, all RSA padding modes are applicable only to certain purposes. Specifically, PaddingMode::RSA_PKCS1_1_5_SIGN and PaddingMode::RSA_PSS only support signing and verification, while PaddingMode::RSA_PKCS1_1_1_5_ENCRYPT and PaddingMode::RSA_OAEP only support encryption and decryption. The method returns ErrorCode::UNSUPPORTED_PADDING_MODE if the specified mode does not support the specified purpose.

There are some important interactions between padding modes and digests:

  • PaddingMode::NONE indicates that a "raw" RSA operation is performed. If signing or verifying, Digest::NONE is specified for the digest. No digest is necessary for unpadded encryption or decryption.
  • PaddingMode::RSA_PKCS1_1_5_SIGN padding requires a digest. The digest may be Digest::NONE, in which case the Keymaster implementation cannot build a proper PKCS#1 v1.5 signature structure, because it cannot add the DigestInfo structure. Instead, the implementation constructs 0x00 || 0x01 || PS || 0x00 || M, where M is the provided message and PS is the padding string. The size of the RSA key has to be at least 11 bytes larger than the message, otherwise the method returns ErrorCode::INVALID_INPUT_LENGTH.
  • PaddingMode::RSA_PKCS1_1_1_5_ENCRYPT padding does not require a digest.
  • PaddingMode::RSA_PSS padding requires a digest, which may not be Digest::NONE. If Digest::NONE is specified, the method returns ErrorCode::INCOMPATIBLE_DIGEST. In addition, the size of the RSA key has to be at least 2 + D bytes larger than the output size of the digest, where D is the size of the digest, in bytes. Otherwise the method returns ErrorCode::INCOMPATIBLE_DIGEST. The salt size is D.
  • PaddingMode::RSA_OAEP padding requires a digest, which may not be Digest::NONE. If Digest::NONE is specified, the method returns ErrorCode::INCOMPATIBLE_DIGEST.

EC keys

EC key operations specify exactly one padding mode in inParams. If unspecified or specified more than once, the method returns ErrorCode::UNSUPPORTED_PADDING_MODE.

Private key operations (KeyPurpose::SIGN) need authorization of digest and padding, which means that the key authorizations need to contain the specified values. If not, return ErrorCode::INCOMPATIBLE_DIGEST. Public key operations (KeyPurpose::VERIFY) are permitted with unauthorized digest or padding.

AES keys

AES key operations specify exactly one block mode and one padding mode in inParams. If either value is unspecified or specified more than once, return ErrorCode::UNSUPPORTED_BLOCK_MODE or ErrorCode::UNSUPPORTED_PADDING_MODE. The specified modes have to be authorized by the key, otherwise the method returns ErrorCode::INCOMPATIBLE_BLOCK_MODE or ErrorCode::INCOMPATIBLE_PADDING_MODE.

If the block mode is BlockMode::GCM, inParams specifies Tag::MAC_LENGTH, and the specified value is a multiple of 8 that is not greater than 128 or less than the value of Tag::MIN_MAC_LENGTH in the key authorizations. For MAC lengths greater than 128 or non-multiples of 8, return ErrorCode::UNSUPPORTED_MAC_LENGTH. For values less than the key's minimum length, return ErrorCode::INVALID_MAC_LENGTH.

If the block mode is BlockMode::GCM or BlockMode::CTR, the specified padding mode has to be PaddingMode::NONE. For BlockMode::ECB or BlockMode::CBC, the mode may be PaddingMode::NONE or PaddingMode::PKCS7. If the padding mode doesn't meet these conditions, return ErrorCode::INCOMPATIBLE_PADDING_MODE.

If the block mode is BlockMode::CBC, BlockMode::CTR, or BlockMode::GCM, an initialization vector or nonce is needed. In most cases, callers shouldn't provide an IV or nonce. In that case, the Keymaster implementation generates a random IV or nonce and returns it via Tag::NONCE in outParams. CBC and CTR IVs are 16 bytes. GCM nonces are 12 bytes. If the key authorizations contain Tag::CALLER_NONCE, then the caller may provide an IV/nonce with Tag::NONCE in inParams. If a nonce is provided when Tag::CALLER_NONCE is not authorized, return ErrorCode::CALLER_NONCE_PROHIBITED. If a nonce is not provided when Tag::CALLER_NONCE is authorized, generate a random IV/nonce.

HMAC keys

HMAC key operations specify Tag::MAC_LENGTH in inParams. The specified value must be a multiple of 8 that is not greater than the digest length or less than the value of Tag::MIN_MAC_LENGTH in the key authorizations. For MAC lengths greater than the digest length or non-multiples of 8, return ErrorCode::UNSUPPORTED_MAC_LENGTH. For values less than the key's minimum length, return ErrorCode::INVALID_MAC_LENGTH.

update

Version: 1, 2, 3

Provides data to process in an ongoing operation started with begin. The operation is specified by the operationHandle parameter.

To provide more flexibility for buffer handling, implementations of this method have the option of consuming less data than was provided. The caller is responsible for looping to feed the rest of the data in subsequent calls. The amount of input consumed is returned in the inputConsumed parameter. Implementations always consume at least one byte, unless the operation cannot accept any more; if more than zero bytes are provided and zero bytes are consumed, callers consider this an error and abort the operation.

Implementations may also choose how much data to return, as a result of the update. This is only relevant for encryption and decryption operations, because signing and verification return no data until finish. Return data as early as possible, rather than buffer it.

Error handling

If this method returns an error code other than ErrorCode::OK, the operation is aborted and the operation handle is invalidated. Any future use of the handle, with this method, finish, or abort, returns ErrorCode::INVALID_OPERATION_HANDLE.

Authorization enforcement

Key authorization enforcement is performed primarily in begin. The one exception is the case where the key has:

In this case, the key requires an authorization per operation, and the update method receives a Tag::AUTH_TOKEN in the inParams argument. HMAC verifies that the token is valid and contains a matching secure user ID, matches the key's Tag::USER_AUTH_TYPE, and contains the operation handle of the current operation in the challenge field. If these conditions aren't met, return ErrorCode::KEY_USER_NOT_AUTHENTICATED.

The caller provides the authentication token to every call to update and finish. The implementation need only validate the token once if it prefers.

RSA keys

For signing and verification operations with Digest::NONE, this method accepts the entire block to be signed or verified in a single update. It may not consume only a portion of the block. However, if the caller chooses to provide the data in multiple updates, this method accepts it. If the caller provides more data to sign than can be used (length of data exceeds RSA key size), return ErrorCode::INVALID_INPUT_LENGTH.

ECDSA keys

For signing and verification operations with Digest::NONE, this method accepts the entire block to be signed or verified in a single update. This method may not consume only a portion of the block.

However, if the caller chooses to provide the data in multiple updates, this method accepts it. If the caller provides more data to sign than can be used, the data is silently truncated. (This differs from the handling of excess data provided in similar RSA operations. The reason for this is compatibility with legacy clients.)

AES keys

AES GCM mode supports "associated authentication data," provided via the Tag::ASSOCIATED_DATA tag in the inParams argument. The associated data may be provided in repeated calls (important if the data is too large to send in a single block) but always precedes data to be encrypted or decrypted. An update call may receive both associated data and data to encrypt/decrypt, but subsequent updates may not include associated data. If the caller provides associated data to an update call after a call that includes data to encrypt/decrypt, return ErrorCode::INVALID_TAG.

For GCM encryption, the tag is appended to the ciphertext by finish. During decryption, the last Tag::MAC_LENGTH bytes of the data provided to the last update call is the tag. Since a given invocation of update cannot know if it's the last invocation, it processes all but the tag length and buffer the possible tag data during finish.

finish

Version: 1, 2, 3

Finishes an ongoing operation started with begin, processing all of the as-yet-unprocessed data provided by update(s).

This method is the last one called in an operation, so all processed data is returned.

Whether it completes successfully or returns an error, this method finalizes the operation and therefore invalidates the provided operation handle. Any future use of the handle, with this method or update or abort, returns ErrorCode::INVALID_OPERATION_HANDLE.

Signing operations return the signature as the output. Verification operations accept the signature in the signature parameter, and return no output.

Authorization enforcement

Key authorization enforcement is performed primarily in begin. The one exception is the case where the key has:

In this case, the key requires an authorization per operation, and the update method receives a Tag::AUTH_TOKEN in the inParams argument. HMAC verifies that the token is valid and contains a matching secure user ID, matches the key's Tag::USER_AUTH_TYPE, and contains the operation handle of the current operation in the challenge field. If these conditions aren't met, return ErrorCode::KEY_USER_NOT_AUTHENTICATED.

The caller provides the authentication token to every call to update and finish. The implementation need only validate the token once if it prefers.

RSA keys

Some additional requirements, depending on the padding mode:

  • PaddingMode::NONE. For unpadded signing and encryption operations, if the provided data is shorter than the key, the data is be zero-padded on the left before signing/encryption. If the data is the same length as the key, but numerically larger, return ErrorCode::INVALID_ARGUMENT. For verification and decryption operations, the data must be exactly as long as the key. Otherwise, return ErrorCode::INVALID_INPUT_LENGTH.
  • PaddingMode::RSA_PSS. For PSS-padded signature operations, the PSS salt is at least 20 bytes in length and randomly-generated. The salt may be longer; the reference implementation uses maximally-sized salt. The digest specified with Tag::DIGEST in inputParams on begin is used as the PSS digest algorithm, and SHA1 is used as the MGF1 digest algorithm.
  • PaddingMode::RSA_OAEP. The digest specified with Tag::DIGEST in inputParams on begin is used as the OAEP digest algorithm, and SHA1 is used as the MGF1 digest algorithm.

ECDSA keys

If the data provided for unpadded signing or verification is too long, truncate it.

AES keys

Some additional conditions, depending on block mode:

  • BlockMode::ECB or BlockMode::CBC. If padding is PaddingMode::NONE and the data length is not a multiple of the AES block size, return ErrorCode::INVALID_INPUT_LENGTH. If padding is PaddingMode::PKCS7, pad the data per the PKCS#7 specification. Note that PKCS#7 recommends adding an additional padding block if the data is a multiple of the block length.
  • BlockMode::GCM. During encryption, after processing all plaintext, compute the tag (Tag::MAC_LENGTH bytes) and append it to the returned ciphertext. During decryption, process the last Tag::MAC_LENGTH bytes as the tag. If tag verification fails, return ErrorCode::VERIFICATION_FAILED.

abort

Version: 1, 2, 3

Aborts the in-progress operation. After the call to abort, return ErrorCode::INVALID_OPERATION_HANDLE for any subsequent use of the provided operation handle with update, finish, or abort.

get_supported_algorithms

Version: 1

Returns the list of algorithms supported by the Keymaster hardware implementation. A software implementation returns an empty list; a hybrid implementation returns a list containing only the algorithms that are supported by hardware.

Keymaster 1 implementations support RSA, EC, AES and HMAC.

get_supported_block_modes

Version: 1

Returns the list of AES block modes supported by the Keymaster hardware implementation for a specified algorithm and purpose.

For RSA, EC and HMAC, which are not block ciphers, the method returns an empty list for all valid purposes. Invalid purposes should cause the method to return ErrorCode::INVALID_PURPOSE.

Keymaster 1 implementations support ECB, CBC, CTR and GCM for AES encryption and decryption.

get_supported_padding_modes

Version: 1

Returns the list of padding modes supported by the Keymaster hardware implementation for a specified algorithm and purpose.

HMAC and EC have no notion of padding so the method returns an empty list for all valid purposes. Invalid purposes should cause the method to return ErrorCode::INVALID_PURPOSE.

For RSA, Keymaster 1 implementations support:

  • Unpadded encryption, decryption, signing and verification. For unpadded encryption and signing, if the message is shorter than the public modulus, implementations must left-pad it with zeros. For unpadded decryption and verification, the input length must match the public modulus size.
  • PKCS#1 v1.5 encryption and signing padding modes
  • PSS with a minimum salt length of 20
  • OAEP

For AES in ECB and CBC modes, Keymaster 1 implementations support no padding and PKCS#7-padding. CTR and GCM modes support only no padding.

get_supported_digests

Version: 1

Returns the list of digest modes supported by the Keymaster hardware implementation for a specified algorithm and purpose.

No AES modes support or require digesting, so the method returns an empty list for valid purposes.

Keymaster 1 implementations can implement a subset of the defined digests. Implementations provide SHA-256 and can provide MD5, SHA1, SHA-224, SHA-256, SHA384 and SHA512 (the full set of defined digests).

get_supported_import_formats

Version: 1

Returns the list of import formats supported by the Keymaster hardware implementation of a specified algorithm.

Keymaster 1 implementations support the PKCS#8 format (without password protection) for importing RSA and EC key pairs, and support RAW import of AES and HMAC key material.

get_supported_export_formats

Version: 1

Returns the list of export formats supported by the Keymaster hardware implementation of a specified algorithm.

Keymaster1 implementations support the X.509 format for exporting RSA and EC public keys. Export of private keys or asymmetric keys is not supported.

Historical functions

Keymaster 0

The following functions belong to the original Keymaster 0 definition. They were present in Keymaster 1 struct keymaster1_device_t. However, in Keymaster 1.0 they were not implemented, and their function pointers were set to NULL.

  • generate_keypair
  • import_keypair
  • get_keypair_public
  • delete_keypair
  • delete_all
  • sign_data
  • Verify_data

Keymaster 1

The following functions belong to the Keymaster 1 definition, but were removed in Keymaster 2, along with the Keymaster 0 functions listed above.

  • get_supported_algorithms
  • get_supported_block_modes
  • get_supported_padding_modes
  • get_supported_digests
  • get_supported_import_formats
  • get_supported_export_formats

Keymaster 2

The following functions belong to the Keymaster 2 definition, but were removed in Keymaster 3, along with the Keymaster 1 functions listed above.

  • configure