lightbulb_outline Please take our October 2018 developer survey. Start survey

KeyProtection.Builder

public static final class KeyProtection.Builder
extends Object

java.lang.Object
   ↳ android.security.keystore.KeyProtection.Builder


Builder of KeyProtection instances.

Summary

Public constructors

KeyProtection.Builder(int purposes)

Creates a new instance of the Builder.

Public methods

KeyProtection build()

Builds an instance of KeyProtection.

KeyProtection.Builder setBlockModes(String... blockModes)

Sets the set of block modes (e.g., GCM, CBC) with which the key can be used when encrypting/decrypting.

KeyProtection.Builder setDigests(String... digests)

Sets the set of digest algorithms (e.g., SHA-256, SHA-384) with which the key can be used.

KeyProtection.Builder setEncryptionPaddings(String... paddings)

Sets the set of padding schemes (e.g., OAEPPadding, PKCS7Padding, NoPadding) with which the key can be used when encrypting/decrypting.

KeyProtection.Builder setInvalidatedByBiometricEnrollment(boolean invalidateKey)

Sets whether this key should be invalidated on fingerprint enrollment.

KeyProtection.Builder setKeyValidityEnd(Date endDate)

Sets the time instant after which the key is no longer valid.

KeyProtection.Builder setKeyValidityForConsumptionEnd(Date endDate)

Sets the time instant after which the key is no longer valid for decryption and verification.

KeyProtection.Builder setKeyValidityForOriginationEnd(Date endDate)

Sets the time instant after which the key is no longer valid for encryption and signing.

KeyProtection.Builder setKeyValidityStart(Date startDate)

Sets the time instant before which the key is not yet valid.

KeyProtection.Builder setRandomizedEncryptionRequired(boolean required)

Sets whether encryption using this key must be sufficiently randomized to produce different ciphertexts for the same plaintext every time.

KeyProtection.Builder setSignaturePaddings(String... paddings)

Sets the set of padding schemes (e.g., PSS, PKCS#1) with which the key can be used when signing/verifying.

KeyProtection.Builder setUnlockedDeviceRequired(boolean unlockedDeviceRequired)

Sets whether the keystore requires the screen to be unlocked before allowing decryption using this key.

KeyProtection.Builder setUserAuthenticationRequired(boolean required)

Sets whether this key is authorized to be used only if the user has been authenticated.

KeyProtection.Builder setUserAuthenticationValidWhileOnBody(boolean remainsValid)

Sets whether the key will remain authorized only until the device is removed from the user's body up to the limit of the authentication validity period (see setUserAuthenticationValidityDurationSeconds(int) and setUserAuthenticationRequired(boolean)).

KeyProtection.Builder setUserAuthenticationValidityDurationSeconds(int seconds)

Sets the duration of time (seconds) for which this key is authorized to be used after the user is successfully authenticated.

KeyProtection.Builder setUserConfirmationRequired(boolean required)

Sets whether this key is authorized to be used only for messages confirmed by the user.

KeyProtection.Builder setUserPresenceRequired(boolean required)

Sets whether a test of user presence is required to be performed between the Signature.initSign() and Signature.sign() method calls.

Inherited methods

Public constructors

KeyProtection.Builder

added in API level 23
public KeyProtection.Builder (int purposes)

Creates a new instance of the Builder.

Parameters
purposes int: set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used. Attempts to use the key for any other purpose will be rejected.

See KeyProperties.PURPOSE flags.

Value is either 0 or combination of PURPOSE_ENCRYPT, PURPOSE_DECRYPT, PURPOSE_SIGN, PURPOSE_VERIFY or PURPOSE_WRAP_KEY.

Public methods

build

added in API level 23
public KeyProtection build ()

Builds an instance of KeyProtection.

Returns
KeyProtection

This value will never be null.

Throws
IllegalArgumentException if a required field is missing

setBlockModes

added in API level 23
public KeyProtection.Builder setBlockModes (String... blockModes)

Sets the set of block modes (e.g., GCM, CBC) with which the key can be used when encrypting/decrypting. Attempts to use the key with any other block modes will be rejected.

This must be specified for symmetric encryption/decryption keys.

See KeyProperties.BLOCK_MODE constants.

Parameters
blockModes String

Value is BLOCK_MODE_ECB, BLOCK_MODE_CBC, BLOCK_MODE_CTR or BLOCK_MODE_GCM.

Returns
KeyProtection.Builder

This value will never be null.

setDigests

added in API level 23
public KeyProtection.Builder setDigests (String... digests)

Sets the set of digest algorithms (e.g., SHA-256, SHA-384) with which the key can be used. Attempts to use the key with any other digest algorithm will be rejected.

This must be specified for signing/verification keys and RSA encryption/decryption keys used with RSA OAEP padding scheme because these operations involve a digest. For HMAC keys, the default is the digest specified in Key.getAlgorithm() (e.g., SHA-256 for key algorithm HmacSHA256). HMAC keys cannot be authorized for more than one digest.

For private keys used for TLS/SSL client or server authentication it is usually necessary to authorize the use of no digest (KeyProperties.DIGEST_NONE). This is because TLS/SSL stacks typically generate the necessary digest(s) themselves and then use a private key to sign it.

See KeyProperties.DIGEST constants.

Parameters
digests String

Value is DIGEST_NONE, DIGEST_MD5, DIGEST_SHA1, DIGEST_SHA224, DIGEST_SHA256, DIGEST_SHA384 or DIGEST_SHA512.

Returns
KeyProtection.Builder

This value will never be null.

setEncryptionPaddings

added in API level 23
public KeyProtection.Builder setEncryptionPaddings (String... paddings)

Sets the set of padding schemes (e.g., OAEPPadding, PKCS7Padding, NoPadding) with which the key can be used when encrypting/decrypting. Attempts to use the key with any other padding scheme will be rejected.

This must be specified for keys which are used for encryption/decryption.

For RSA private keys used by TLS/SSL servers to authenticate themselves to clients it is usually necessary to authorize the use of no/any padding (KeyProperties.ENCRYPTION_PADDING_NONE) and/or PKCS#1 encryption padding (KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1). This is because RSA decryption is required by some cipher suites, and some stacks request decryption using no padding whereas others request PKCS#1 padding.

See KeyProperties.ENCRYPTION_PADDING constants.

Parameters
paddings String

Value is ENCRYPTION_PADDING_NONE, ENCRYPTION_PADDING_PKCS7, ENCRYPTION_PADDING_RSA_PKCS1 or ENCRYPTION_PADDING_RSA_OAEP.

Returns
KeyProtection.Builder

This value will never be null.

setInvalidatedByBiometricEnrollment

added in API level 24
public KeyProtection.Builder setInvalidatedByBiometricEnrollment (boolean invalidateKey)

Sets whether this key should be invalidated on fingerprint enrollment. This applies only to keys which require user authentication (see setUserAuthenticationRequired(boolean)) and if no positive validity duration has been set (see setUserAuthenticationValidityDurationSeconds(int), meaning the key is valid for fingerprint authentication only.

By default, invalidateKey is true, so keys that are valid for fingerprint authentication only are irreversibly invalidated when a new fingerprint is enrolled, or when all existing fingerprints are deleted. That may be changed by calling this method with invalidateKey set to false.

Invalidating keys on enrollment of a new finger or unenrollment of all fingers improves security by ensuring that an unauthorized person who obtains the password can't gain the use of fingerprint-authenticated keys by enrolling their own finger. However, invalidating keys makes key-dependent operations impossible, requiring some fallback procedure to authenticate the user and set up a new key.

Parameters
invalidateKey boolean

Returns
KeyProtection.Builder

This value will never be null.

setKeyValidityEnd

added in API level 23
public KeyProtection.Builder setKeyValidityEnd (Date endDate)

Sets the time instant after which the key is no longer valid.

By default, the key is valid at any instant.

Parameters
endDate Date

Returns
KeyProtection.Builder

This value will never be null.

setKeyValidityForConsumptionEnd

added in API level 23
public KeyProtection.Builder setKeyValidityForConsumptionEnd (Date endDate)

Sets the time instant after which the key is no longer valid for decryption and verification.

By default, the key is valid at any instant.

Parameters
endDate Date

Returns
KeyProtection.Builder

This value will never be null.

setKeyValidityForOriginationEnd

added in API level 23
public KeyProtection.Builder setKeyValidityForOriginationEnd (Date endDate)

Sets the time instant after which the key is no longer valid for encryption and signing.

By default, the key is valid at any instant.

Parameters
endDate Date

Returns
KeyProtection.Builder

This value will never be null.

setKeyValidityStart

added in API level 23
public KeyProtection.Builder setKeyValidityStart (Date startDate)

Sets the time instant before which the key is not yet valid.

By default, the key is valid at any instant.

Parameters
startDate Date

Returns
KeyProtection.Builder

This value will never be null.

setRandomizedEncryptionRequired

added in API level 23
public KeyProtection.Builder setRandomizedEncryptionRequired (boolean required)

Sets whether encryption using this key must be sufficiently randomized to produce different ciphertexts for the same plaintext every time. The formal cryptographic property being required is indistinguishability under chosen-plaintext attack (IND-CPA). This property is important because it mitigates several classes of weaknesses due to which ciphertext may leak information about plaintext. For example, if a given plaintext always produces the same ciphertext, an attacker may see the repeated ciphertexts and be able to deduce something about the plaintext.

By default, IND-CPA is required.

When IND-CPA is required:

  • transformation which do not offer IND-CPA, such as symmetric ciphers using ECB mode or RSA encryption without padding, are prohibited;
  • in transformations which use an IV, such as symmetric ciphers in GCM, CBC, and CTR block modes, caller-provided IVs are rejected when encrypting, to ensure that only random IVs are used.
  • Before disabling this requirement, consider the following approaches instead:

    • If you are generating a random IV for encryption and then initializing a Cipher using the IV, the solution is to let the Cipher generate a random IV instead. This will occur if the Cipher is initialized for encryption without an IV. The IV can then be queried via Cipher.getIV().
    • If you are generating a non-random IV (e.g., an IV derived from something not fully random, such as the name of the file being encrypted, or transaction ID, or password, or a device identifier), consider changing your design to use a random IV which will then be provided in addition to the ciphertext to the entities which need to decrypt the ciphertext.
    • If you are using RSA encryption without padding, consider switching to padding schemes which offer IND-CPA, such as PKCS#1 or OAEP.

    Parameters
    required boolean

    Returns
    KeyProtection.Builder

    This value will never be null.

setSignaturePaddings

added in API level 23
public KeyProtection.Builder setSignaturePaddings (String... paddings)

Sets the set of padding schemes (e.g., PSS, PKCS#1) with which the key can be used when signing/verifying. Attempts to use the key with any other padding scheme will be rejected.

This must be specified for RSA keys which are used for signing/verification.

See KeyProperties.SIGNATURE_PADDING constants.

Parameters
paddings String

Value is SIGNATURE_PADDING_RSA_PKCS1 or SIGNATURE_PADDING_RSA_PSS.

Returns
KeyProtection.Builder

This value will never be null.

setUnlockedDeviceRequired

added in API level 28
public KeyProtection.Builder setUnlockedDeviceRequired (boolean unlockedDeviceRequired)

Sets whether the keystore requires the screen to be unlocked before allowing decryption using this key. If this is set to true, any attempt to decrypt or sign using this key while the screen is locked will fail. A locked device requires a PIN, password, fingerprint, or other trusted factor to access. While the screen is locked, the key can still be used for encryption or signature verification.

Parameters
unlockedDeviceRequired boolean

Returns
KeyProtection.Builder

This value will never be null.

setUserAuthenticationRequired

added in API level 23
public KeyProtection.Builder setUserAuthenticationRequired (boolean required)

Sets whether this key is authorized to be used only if the user has been authenticated.

By default, the key is authorized to be used regardless of whether the user has been authenticated.

When user authentication is required:

  • The key can only be import if secure lock screen is set up (see KeyguardManager.isDeviceSecure()). Additionally, if the key requires that user authentication takes place for every use of the key (see setUserAuthenticationValidityDurationSeconds(int)), at least one fingerprint must be enrolled (see FingerprintManager.hasEnrolledFingerprints()).
  • The use of the key must be authorized by the user by authenticating to this Android device using a subset of their secure lock screen credentials such as password/PIN/pattern or fingerprint. More information.
  • The key will become irreversibly invalidated once the secure lock screen is disabled (reconfigured to None, Swipe or other mode which does not authenticate the user) or when the secure lock screen is forcibly reset (e.g., by a Device Administrator). Additionally, if the key requires that user authentication takes place for every use of the key, it is also irreversibly invalidated once a new fingerprint is enrolled or once\ * no more fingerprints are enrolled, unless setInvalidatedByBiometricEnrollment(boolean) is used to allow validity after enrollment. Attempts to initialize cryptographic operations using such keys will throw KeyPermanentlyInvalidatedException.

This authorization applies only to secret key and private key operations. Public key operations are not restricted.

Parameters
required boolean

Returns
KeyProtection.Builder

This value will never be null.

setUserAuthenticationValidWhileOnBody

added in API level 24
public KeyProtection.Builder setUserAuthenticationValidWhileOnBody (boolean remainsValid)

Sets whether the key will remain authorized only until the device is removed from the user's body up to the limit of the authentication validity period (see setUserAuthenticationValidityDurationSeconds(int) and setUserAuthenticationRequired(boolean)). Once the device has been removed from the user's body, the key will be considered unauthorized and the user will need to re-authenticate to use it. For keys without an authentication validity period this parameter has no effect.

Similarly, on devices that do not have an on-body sensor, this parameter will have no effect; the device will always be considered to be "on-body" and the key will therefore remain authorized until the validity period ends.

Parameters
remainsValid boolean: if true, and if the device supports on-body detection, key will be invalidated when the device is removed from the user's body or when the authentication validity expires, whichever occurs first.

Returns
KeyProtection.Builder

This value will never be null.

setUserAuthenticationValidityDurationSeconds

added in API level 23
public KeyProtection.Builder setUserAuthenticationValidityDurationSeconds (int seconds)

Sets the duration of time (seconds) for which this key is authorized to be used after the user is successfully authenticated. This has effect if the key requires user authentication for its use (see setUserAuthenticationRequired(boolean)).

By default, if user authentication is required, it must take place for every use of the key.

Cryptographic operations involving keys which require user authentication to take place for every operation can only use fingerprint authentication. This is achieved by initializing a cryptographic operation (Signature, Cipher, Mac) with the key, wrapping it into a FingerprintManager.CryptoObject, invoking FingerprintManager.authenticate with CryptoObject, and proceeding with the cryptographic operation only if the authentication flow succeeds.

Cryptographic operations involving keys which are authorized to be used for a duration of time after a successful user authentication event can only use secure lock screen authentication. These cryptographic operations will throw UserNotAuthenticatedException during initialization if the user needs to be authenticated to proceed. This situation can be resolved by the user unlocking the secure lock screen of the Android or by going through the confirm credential flow initiated by KeyguardManager.createConfirmDeviceCredentialIntent(CharSequence, CharSequence). Once resolved, initializing a new cryptographic operation using this key (or any other key which is authorized to be used for a fixed duration of time after user authentication) should succeed provided the user authentication flow completed successfully.

Parameters
seconds int: duration in seconds or -1 if user authentication must take place for every use of the key.

Value is -1 or greater.

Returns
KeyProtection.Builder

This value will never be null.

setUserConfirmationRequired

added in API level 28
public KeyProtection.Builder setUserConfirmationRequired (boolean required)

Sets whether this key is authorized to be used only for messages confirmed by the user. Confirmation is separate from user authentication (see setUserAuthenticationRequired(boolean)). Keys can be created that require confirmation but not user authentication, or user authentication but not confirmation, or both. Confirmation verifies that some user with physical possession of the device has approved a displayed message. User authentication verifies that the correct user is present and has authenticated.

This authorization applies only to secret key and private key operations. Public key operations are not restricted.

Parameters
required boolean

Returns
KeyProtection.Builder

This value will never be null.

setUserPresenceRequired

added in API level 28
public KeyProtection.Builder setUserPresenceRequired (boolean required)

Sets whether a test of user presence is required to be performed between the Signature.initSign() and Signature.sign() method calls. It requires that the KeyStore implementation have a direct way to validate the user presence for example a KeyStore hardware backed strongbox can use a button press that is observable in hardware. A test for user presence is tangential to authentication. The test can be part of an authentication step as long as this step can be validated by the hardware protecting the key and cannot be spoofed. For example, a physical button press can be used as a test of user presence if the other pins connected to the button are not able to simulate a button press. There must be no way for the primary processor to fake a button press, or that button must not be used as a test of user presence.

Parameters
required boolean

Returns
KeyProtection.Builder

This value will never be null.