am 4b79bbea: am 558184f5: Merge "Make the new AndroidKeyStore API conformant."

* commit '4b79bbeaa3c6a8820fe83aa75179b6cae550320f':
  Make the new AndroidKeyStore API conformant.
This commit is contained in:
Alex Klyubin
2015-04-07 18:07:53 +00:00
committed by Android Git Automerger
9 changed files with 474 additions and 699 deletions

View File

@ -171,6 +171,9 @@ public final class KeymasterDefs {
public static final int KM_KEY_FORMAT_PKCS12 = 2; public static final int KM_KEY_FORMAT_PKCS12 = 2;
public static final int KM_KEY_FORMAT_RAW = 3; public static final int KM_KEY_FORMAT_RAW = 3;
// User authenticators.
public static final int HW_AUTH_PASSWORD = 1 << 0;
// Error codes. // Error codes.
public static final int KM_ERROR_OK = 0; public static final int KM_ERROR_OK = 0;
public static final int KM_ERROR_ROOT_OF_TRUST_ALREADY_SET = -1; public static final int KM_ERROR_ROOT_OF_TRUST_ALREADY_SET = -1;

View File

@ -466,81 +466,72 @@ public class AndroidKeyStore extends KeyStoreSpi {
throw new KeyStoreException("Unsupported secret key algorithm: " + keyAlgorithmString); throw new KeyStoreException("Unsupported secret key algorithm: " + keyAlgorithmString);
} }
if ((params.getAlgorithm() != null) && (params.getAlgorithm() != keyAlgorithm)) {
throw new KeyStoreException("Key algorithm mismatch. Key: " + keyAlgorithmString
+ ", parameter spec: "
+ KeyStoreKeyConstraints.Algorithm.toString(params.getAlgorithm()));
}
KeymasterArguments args = new KeymasterArguments(); KeymasterArguments args = new KeymasterArguments();
args.addInt(KeymasterDefs.KM_TAG_ALGORITHM, args.addInt(KeymasterDefs.KM_TAG_ALGORITHM,
KeyStoreKeyConstraints.Algorithm.toKeymaster(keyAlgorithm)); KeyStoreKeyConstraints.Algorithm.toKeymaster(keyAlgorithm));
if (digest != null) { @KeyStoreKeyConstraints.DigestEnum int digests;
// Digest available from JCA key algorithm if (params.isDigestsSpecified()) {
if (params.getDigest() != null) { // Digest(s) specified in parameters
// Digest also specified in parameters -- check that these two match if (digest != null) {
if (digest != params.getDigest()) { // Digest also specified in the JCA key algorithm name.
throw new KeyStoreException("Key digest mismatch. Key: " + keyAlgorithmString if ((params.getDigests() & digest) != digest) {
throw new KeyStoreException("Key digest mismatch"
+ ". Key: " + keyAlgorithmString
+ ", parameter spec: " + ", parameter spec: "
+ KeyStoreKeyConstraints.Digest.toString(params.getDigest())); + KeyStoreKeyConstraints.Digest.allToString(params.getDigests()));
} }
} }
digests = params.getDigests();
} else { } else {
// Digest not available from JCA key algorithm // No digest specified in parameters
digest = params.getDigest(); if (digest != null) {
// Digest specified in the JCA key algorithm name.
digests = digest;
} else {
digests = 0;
}
} }
if (digest != null) { for (int keymasterDigest : KeyStoreKeyConstraints.Digest.allToKeymaster(digests)) {
args.addInt(KeymasterDefs.KM_TAG_DIGEST, args.addInt(KeymasterDefs.KM_TAG_DIGEST, keymasterDigest);
KeyStoreKeyConstraints.Digest.toKeymaster(digest)); }
if (digests != 0) {
// TODO: Remove MAC length constraint once Keymaster API no longer requires it.
// This code will blow up if mode than one digest is specified.
Integer digestOutputSizeBytes = Integer digestOutputSizeBytes =
KeyStoreKeyConstraints.Digest.getOutputSizeBytes(digest); KeyStoreKeyConstraints.Digest.getOutputSizeBytes(digest);
if (digestOutputSizeBytes != null) { if (digestOutputSizeBytes != null) {
// TODO: Remove MAC length constraint once Keymaster API no longer requires it.
// TODO: Switch to bits instead of bytes, once this is fixed in Keymaster // TODO: Switch to bits instead of bytes, once this is fixed in Keymaster
args.addInt(KeymasterDefs.KM_TAG_MAC_LENGTH, digestOutputSizeBytes); args.addInt(KeymasterDefs.KM_TAG_MAC_LENGTH, digestOutputSizeBytes);
} }
} }
if (keyAlgorithm == KeyStoreKeyConstraints.Algorithm.HMAC) { if (keyAlgorithm == KeyStoreKeyConstraints.Algorithm.HMAC) {
if (digest == null) { if (digests == 0) {
throw new IllegalStateException("Digest algorithm must be specified for key" throw new KeyStoreException("At least one digest algorithm must be specified"
+ " algorithm " + keyAlgorithmString); + " for key algorithm " + keyAlgorithmString);
} }
} }
@KeyStoreKeyConstraints.PurposeEnum int purposes = (params.getPurposes() != null) int purposes = params.getPurposes();
? params.getPurposes() for (int keymasterPurpose : KeyStoreKeyConstraints.Purpose.allToKeymaster(purposes)) {
: (KeyStoreKeyConstraints.Purpose.ENCRYPT
| KeyStoreKeyConstraints.Purpose.DECRYPT
| KeyStoreKeyConstraints.Purpose.SIGN
| KeyStoreKeyConstraints.Purpose.VERIFY);
for (int keymasterPurpose :
KeyStoreKeyConstraints.Purpose.allToKeymaster(purposes)) {
args.addInt(KeymasterDefs.KM_TAG_PURPOSE, keymasterPurpose); args.addInt(KeymasterDefs.KM_TAG_PURPOSE, keymasterPurpose);
} }
if (params.getBlockMode() != null) { for (int keymasterBlockMode :
args.addInt(KeymasterDefs.KM_TAG_BLOCK_MODE, KeyStoreKeyConstraints.BlockMode.allToKeymaster(params.getBlockModes())) {
KeyStoreKeyConstraints.BlockMode.toKeymaster(params.getBlockMode())); args.addInt(KeymasterDefs.KM_TAG_BLOCK_MODE, keymasterBlockMode);
} }
if (params.getPadding() != null) { for (int keymasterPadding :
args.addInt(KeymasterDefs.KM_TAG_PADDING, KeyStoreKeyConstraints.Padding.allToKeymaster(params.getPaddings())) {
KeyStoreKeyConstraints.Padding.toKeymaster(params.getPadding())); args.addInt(KeymasterDefs.KM_TAG_PADDING, keymasterPadding);
} }
if (params.getMaxUsesPerBoot() != null) { if (params.getUserAuthenticators() == 0) {
args.addInt(KeymasterDefs.KM_TAG_MAX_USES_PER_BOOT, params.getMaxUsesPerBoot());
}
if (params.getMinSecondsBetweenOperations() != null) {
args.addInt(KeymasterDefs.KM_TAG_MIN_SECONDS_BETWEEN_OPS,
params.getMinSecondsBetweenOperations());
}
if (params.getUserAuthenticators().isEmpty()) {
args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED); args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
} else { } else {
args.addInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, args.addInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE,
KeyStoreKeyConstraints.UserAuthenticator.allToKeymaster( KeyStoreKeyConstraints.UserAuthenticator.allToKeymaster(
params.getUserAuthenticators())); params.getUserAuthenticators()));
} }
if (params.getUserAuthenticationValidityDurationSeconds() != null) { if (params.getUserAuthenticationValidityDurationSeconds() != -1) {
args.addInt(KeymasterDefs.KM_TAG_AUTH_TIMEOUT, args.addInt(KeymasterDefs.KM_TAG_AUTH_TIMEOUT,
params.getUserAuthenticationValidityDurationSeconds()); params.getUserAuthenticationValidityDurationSeconds());
} }

View File

@ -19,12 +19,8 @@ package android.security;
import android.content.Context; import android.content.Context;
import android.text.TextUtils; import android.text.TextUtils;
import java.security.cert.Certificate;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.crypto.KeyGenerator; import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
@ -33,13 +29,13 @@ import javax.crypto.SecretKey;
* {@link AlgorithmParameterSpec} for initializing a {@code KeyGenerator} that works with * {@link AlgorithmParameterSpec} for initializing a {@code KeyGenerator} that works with
* <a href="{@docRoot}training/articles/keystore.html">Android KeyStore facility</a>. * <a href="{@docRoot}training/articles/keystore.html">Android KeyStore facility</a>.
* *
* <p>The Android KeyStore facility is accessed through a {@link KeyGenerator} API * <p>The Android KeyStore facility is accessed through a {@link KeyGenerator} API using the
* using the {@code AndroidKeyStore} provider. The {@code context} passed in may be used to pop up * {@code AndroidKeyStore} provider. The {@code context} passed in may be used to pop up some UI to
* some UI to ask the user to unlock or initialize the Android KeyStore facility. * ask the user to unlock or initialize the Android KeyStore facility.
* *
* <p>After generation, the {@code keyStoreAlias} is used with the * <p>After generation, the {@code keyStoreAlias} is used with the
* {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter)} * {@link java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter)}
* interface to retrieve the {@link SecretKey} and its associated {@link Certificate} chain. * interface to retrieve the {@link SecretKey}.
* *
* @hide * @hide
*/ */
@ -52,13 +48,11 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
private final Date mKeyValidityStart; private final Date mKeyValidityStart;
private final Date mKeyValidityForOriginationEnd; private final Date mKeyValidityForOriginationEnd;
private final Date mKeyValidityForConsumptionEnd; private final Date mKeyValidityForConsumptionEnd;
private final @KeyStoreKeyConstraints.PurposeEnum Integer mPurposes; private final @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private final @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private final @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private final @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private final @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private final Integer mMinSecondsBetweenOperations; private final @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private final Integer mMaxUsesPerBoot; private final int mUserAuthenticationValidityDurationSeconds;
private final Set<Integer> mUserAuthenticators;
private final Integer mUserAuthenticationValidityDurationSeconds;
private KeyGeneratorSpec( private KeyGeneratorSpec(
Context context, Context context,
@ -68,19 +62,17 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
Date keyValidityStart, Date keyValidityStart,
Date keyValidityForOriginationEnd, Date keyValidityForOriginationEnd,
Date keyValidityForConsumptionEnd, Date keyValidityForConsumptionEnd,
@KeyStoreKeyConstraints.PurposeEnum Integer purposes, @KeyStoreKeyConstraints.PurposeEnum int purposes,
@KeyStoreKeyConstraints.PaddingEnum Integer padding, @KeyStoreKeyConstraints.PaddingEnum int paddings,
@KeyStoreKeyConstraints.BlockModeEnum Integer blockMode, @KeyStoreKeyConstraints.BlockModeEnum int blockModes,
Integer minSecondsBetweenOperations, @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators,
Integer maxUsesPerBoot, int userAuthenticationValidityDurationSeconds) {
Set<Integer> userAuthenticators,
Integer userAuthenticationValidityDurationSeconds) {
if (context == null) { if (context == null) {
throw new IllegalArgumentException("context == null"); throw new IllegalArgumentException("context == null");
} else if (TextUtils.isEmpty(keyStoreAlias)) { } else if (TextUtils.isEmpty(keyStoreAlias)) {
throw new IllegalArgumentException("keyStoreAlias must not be empty"); throw new IllegalArgumentException("keyStoreAlias must not be empty");
} else if ((userAuthenticationValidityDurationSeconds != null) } else if ((userAuthenticationValidityDurationSeconds < 0)
&& (userAuthenticationValidityDurationSeconds < 0)) { && (userAuthenticationValidityDurationSeconds != -1)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"userAuthenticationValidityDurationSeconds must not be negative"); "userAuthenticationValidityDurationSeconds must not be negative");
} }
@ -93,13 +85,9 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
mKeyValidityForOriginationEnd = keyValidityForOriginationEnd; mKeyValidityForOriginationEnd = keyValidityForOriginationEnd;
mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd; mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd;
mPurposes = purposes; mPurposes = purposes;
mPadding = padding; mPaddings = paddings;
mBlockMode = blockMode; mBlockModes = blockModes;
mMinSecondsBetweenOperations = minSecondsBetweenOperations; mUserAuthenticators = userAuthenticators;
mMaxUsesPerBoot = maxUsesPerBoot;
mUserAuthenticators = (userAuthenticators != null)
? new HashSet<Integer>(userAuthenticators)
: Collections.<Integer>emptySet();
mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds; mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
} }
@ -145,8 +133,6 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* Gets the time instant after which the key is no longer valid for decryption and verification. * Gets the time instant after which the key is no longer valid for decryption and verification.
* *
* @return instant or {@code null} if not restricted. * @return instant or {@code null} if not restricted.
*
* @hide
*/ */
public Date getKeyValidityForConsumptionEnd() { public Date getKeyValidityForConsumptionEnd() {
return mKeyValidityForConsumptionEnd; return mKeyValidityForConsumptionEnd;
@ -163,78 +149,43 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
/** /**
* Gets the set of purposes for which the key can be used. * Gets the set of purposes for which the key can be used.
*
* @return set of purposes or {@code null} if the key can be used for any purpose.
*/ */
public @KeyStoreKeyConstraints.PurposeEnum Integer getPurposes() { public @KeyStoreKeyConstraints.PurposeEnum int getPurposes() {
return mPurposes; return mPurposes;
} }
/** /**
* Gets the padding scheme to which the key is restricted. * Gets the set of padding schemes to which the key is restricted.
*
* @return padding scheme or {@code null} if the padding scheme is not restricted.
*/ */
public @KeyStoreKeyConstraints.PaddingEnum Integer getPadding() { public @KeyStoreKeyConstraints.PaddingEnum int getPaddings() {
return mPadding; return mPaddings;
} }
/** /**
* Gets the block mode to which the key is restricted when used for encryption or decryption. * Gets the set of block modes to which the key is restricted.
*
* @return block more or {@code null} if block mode is not restricted.
*
* @hide
*/ */
public @KeyStoreKeyConstraints.BlockModeEnum Integer getBlockMode() { public @KeyStoreKeyConstraints.BlockModeEnum int getBlockModes() {
return mBlockMode; return mBlockModes;
} }
/** /**
* Gets the minimum number of seconds that must expire since the most recent use of the key * Gets the set of user authenticators which protect access to this key. The key can only be
* before it can be used again. * used iff the user has authenticated to at least one of these user authenticators.
* *
* @return number of seconds or {@code null} if there is no restriction on how frequently a key * @return user authenticators or {@code 0} if the key can be used without user authentication.
* can be used.
*
* @hide
*/ */
public Integer getMinSecondsBetweenOperations() { public @KeyStoreKeyConstraints.UserAuthenticatorEnum int getUserAuthenticators() {
return mMinSecondsBetweenOperations; return mUserAuthenticators;
}
/**
* Gets the number of times the key can be used without rebooting the device.
*
* @return maximum number of times or {@code null} if there is no restriction.
* @hide
*/
public Integer getMaxUsesPerBoot() {
return mMaxUsesPerBoot;
}
/**
* Gets the user authenticators which protect access to this key. The key can only be used iff
* the user has authenticated to at least one of these user authenticators.
*
* @return user authenticators or empty set if the key can be used without user authentication.
*
* @hide
*/
public Set<Integer> getUserAuthenticators() {
return new HashSet<Integer>(mUserAuthenticators);
} }
/** /**
* Gets the duration of time (seconds) for which this key can be used after the user * Gets the duration of time (seconds) for which this key can be used after the user
* successfully authenticates to one of the associated user authenticators. * successfully authenticates to one of the associated user authenticators.
* *
* @return duration in seconds or {@code null} if not restricted. {@code 0} means authentication * @return duration in seconds or {@code -1} if not restricted. {@code 0} means authentication
* is required for every use of the key. * is required for every use of the key.
*
* @hide
*/ */
public Integer getUserAuthenticationValidityDurationSeconds() { public int getUserAuthenticationValidityDurationSeconds() {
return mUserAuthenticationValidityDurationSeconds; return mUserAuthenticationValidityDurationSeconds;
} }
@ -253,13 +204,11 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
private Date mKeyValidityStart; private Date mKeyValidityStart;
private Date mKeyValidityForOriginationEnd; private Date mKeyValidityForOriginationEnd;
private Date mKeyValidityForConsumptionEnd; private Date mKeyValidityForConsumptionEnd;
private @KeyStoreKeyConstraints.PurposeEnum Integer mPurposes; private @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private Integer mMinSecondsBetweenOperations; private @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private Integer mMaxUsesPerBoot; private int mUserAuthenticationValidityDurationSeconds = -1;
private Set<Integer> mUserAuthenticators;
private Integer mUserAuthenticationValidityDurationSeconds;
/** /**
* Creates a new instance of the {@code Builder} with the given {@code context}. The * Creates a new instance of the {@code Builder} with the given {@code context}. The
@ -318,8 +267,6 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* <b>By default, the key is valid at any instant. * <b>By default, the key is valid at any instant.
* *
* @see #setKeyValidityEnd(Date) * @see #setKeyValidityEnd(Date)
*
* @hide
*/ */
public Builder setKeyValidityStart(Date startDate) { public Builder setKeyValidityStart(Date startDate) {
mKeyValidityStart = startDate; mKeyValidityStart = startDate;
@ -334,8 +281,6 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* @see #setKeyValidityStart(Date) * @see #setKeyValidityStart(Date)
* @see #setKeyValidityForConsumptionEnd(Date) * @see #setKeyValidityForConsumptionEnd(Date)
* @see #setKeyValidityForOriginationEnd(Date) * @see #setKeyValidityForOriginationEnd(Date)
*
* @hide
*/ */
public Builder setKeyValidityEnd(Date endDate) { public Builder setKeyValidityEnd(Date endDate) {
setKeyValidityForOriginationEnd(endDate); setKeyValidityForOriginationEnd(endDate);
@ -349,8 +294,6 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* <b>By default, the key is valid at any instant. * <b>By default, the key is valid at any instant.
* *
* @see #setKeyValidityForConsumptionEnd(Date) * @see #setKeyValidityForConsumptionEnd(Date)
*
* @hide
*/ */
public Builder setKeyValidityForOriginationEnd(Date endDate) { public Builder setKeyValidityForOriginationEnd(Date endDate) {
mKeyValidityForOriginationEnd = endDate; mKeyValidityForOriginationEnd = endDate;
@ -364,8 +307,6 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* <b>By default, the key is valid at any instant. * <b>By default, the key is valid at any instant.
* *
* @see #setKeyValidityForOriginationEnd(Date) * @see #setKeyValidityForOriginationEnd(Date)
*
* @hide
*/ */
public Builder setKeyValidityForConsumptionEnd(Date endDate) { public Builder setKeyValidityForConsumptionEnd(Date endDate) {
mKeyValidityForConsumptionEnd = endDate; mKeyValidityForConsumptionEnd = endDate;
@ -373,11 +314,9 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
} }
/** /**
* Restricts the purposes for which the key can be used to the provided set of purposes. * Restricts the key to being used only for the provided set of purposes.
* *
* <p>By default, the key can be used for encryption, decryption, signing, and verification. * <p>This restriction must be specified. There is no default.
*
* @hide
*/ */
public Builder setPurposes(@KeyStoreKeyConstraints.PurposeEnum int purposes) { public Builder setPurposes(@KeyStoreKeyConstraints.PurposeEnum int purposes) {
mPurposes = purposes; mPurposes = purposes;
@ -385,53 +324,24 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
} }
/** /**
* Restricts the key to being used only with the provided padding scheme. Attempts to use * Restricts the key to being used only with the provided padding schemes. Attempts to use
* the key with any other padding will be rejected. * the key with any other padding will be rejected.
* *
* <p>This restriction must be specified for keys which are used for encryption/decryption. * <p>This restriction must be specified for keys which are used for encryption/decryption.
*
* @hide
*/ */
public Builder setPadding(@KeyStoreKeyConstraints.PaddingEnum int padding) { public Builder setPaddings(@KeyStoreKeyConstraints.PaddingEnum int paddings) {
mPadding = padding; mPaddings = paddings;
return this; return this;
} }
/** /**
* Restricts the key to being used only with the provided block mode when encrypting or * Restricts the key to being used only with the provided block modes. Attempts to use the
* decrypting. Attempts to use the key with any other block modes will be rejected. * key with any other block modes will be rejected.
* *
* <p>This restriction must be specified for keys which are used for encryption/decryption. * <p>This restriction must be specified for keys which are used for encryption/decryption.
*
* @hide
*/ */
public Builder setBlockMode(@KeyStoreKeyConstraints.BlockModeEnum int blockMode) { public Builder setBlockModes(@KeyStoreKeyConstraints.BlockModeEnum int blockModes) {
mBlockMode = blockMode; mBlockModes = blockModes;
return this;
}
/**
* Sets the minimum number of seconds that must expire since the most recent use of the key
* before it can be used again.
*
* <p>By default, there is no restriction on how frequently a key can be used.
*
* @hide
*/
public Builder setMinSecondsBetweenOperations(int seconds) {
mMinSecondsBetweenOperations = seconds;
return this;
}
/**
* Sets the maximum number of times a key can be used without rebooting the device.
*
* <p>By default, the key can be used for an unlimited number of times.
*
* @hide
*/
public Builder setMaxUsesPerBoot(int count) {
mMaxUsesPerBoot = count;
return this; return this;
} }
@ -445,12 +355,10 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* without user authentication. * without user authentication.
* *
* @see #setUserAuthenticationValidityDurationSeconds(int) * @see #setUserAuthenticationValidityDurationSeconds(int)
*
* @hide
*/ */
public Builder setUserAuthenticators(Set<Integer> userAuthenticators) { public Builder setUserAuthenticators(
mUserAuthenticators = @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators) {
(userAuthenticators != null) ? new HashSet<Integer>(userAuthenticators) : null; mUserAuthenticators = userAuthenticators;
return this; return this;
} }
@ -463,9 +371,7 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* @param seconds duration in seconds or {@code 0} if the user needs to authenticate for * @param seconds duration in seconds or {@code 0} if the user needs to authenticate for
* every use of the key. * every use of the key.
* *
* @see #setUserAuthenticators(Set) * @see #setUserAuthenticators(int)
*
* @hide
*/ */
public Builder setUserAuthenticationValidityDurationSeconds(int seconds) { public Builder setUserAuthenticationValidityDurationSeconds(int seconds) {
mUserAuthenticationValidityDurationSeconds = seconds; mUserAuthenticationValidityDurationSeconds = seconds;
@ -478,10 +384,18 @@ public class KeyGeneratorSpec implements AlgorithmParameterSpec {
* @throws IllegalArgumentException if a required field is missing or violates a constraint. * @throws IllegalArgumentException if a required field is missing or violates a constraint.
*/ */
public KeyGeneratorSpec build() { public KeyGeneratorSpec build() {
return new KeyGeneratorSpec(mContext, mKeystoreAlias, mFlags, mKeySize, return new KeyGeneratorSpec(mContext,
mKeyValidityStart, mKeyValidityForOriginationEnd, mKeyValidityForConsumptionEnd, mKeystoreAlias,
mPurposes, mPadding, mBlockMode, mMinSecondsBetweenOperations, mMaxUsesPerBoot, mFlags,
mUserAuthenticators, mUserAuthenticationValidityDurationSeconds); mKeySize,
mKeyValidityStart,
mKeyValidityForOriginationEnd,
mKeyValidityForConsumptionEnd,
mPurposes,
mPaddings,
mBlockModes,
mUserAuthenticators,
mUserAuthenticationValidityDurationSeconds);
} }
} }
} }

View File

@ -24,10 +24,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.cert.Certificate; import java.security.cert.Certificate;
import java.security.spec.AlgorithmParameterSpec; import java.security.spec.AlgorithmParameterSpec;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.x500.X500Principal; import javax.security.auth.x500.X500Principal;
@ -81,21 +78,17 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
private final Date mKeyValidityForConsumptionEnd; private final Date mKeyValidityForConsumptionEnd;
private final @KeyStoreKeyConstraints.PurposeEnum Integer mPurposes; private final @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private final @KeyStoreKeyConstraints.DigestEnum Integer mDigest; private final @KeyStoreKeyConstraints.DigestEnum int mDigests;
private final @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private final @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private final @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private final @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private final Integer mMinSecondsBetweenOperations; private final @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private final Integer mMaxUsesPerBoot; private final int mUserAuthenticationValidityDurationSeconds;
private final Set<Integer> mUserAuthenticators;
private final Integer mUserAuthenticationValidityDurationSeconds;
/** /**
* Parameter specification for the "{@code AndroidKeyPairGenerator}" * Parameter specification for the "{@code AndroidKeyPairGenerator}"
@ -135,14 +128,12 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
Date keyValidityStart, Date keyValidityStart,
Date keyValidityForOriginationEnd, Date keyValidityForOriginationEnd,
Date keyValidityForConsumptionEnd, Date keyValidityForConsumptionEnd,
@KeyStoreKeyConstraints.PurposeEnum Integer purposes, @KeyStoreKeyConstraints.PurposeEnum int purposes,
@KeyStoreKeyConstraints.DigestEnum Integer digest, @KeyStoreKeyConstraints.DigestEnum int digests,
@KeyStoreKeyConstraints.PaddingEnum Integer padding, @KeyStoreKeyConstraints.PaddingEnum int paddings,
@KeyStoreKeyConstraints.BlockModeEnum Integer blockMode, @KeyStoreKeyConstraints.BlockModeEnum int blockModes,
Integer minSecondsBetweenOperations, @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators,
Integer maxUsesPerBoot, int userAuthenticationValidityDurationSeconds) {
Set<Integer> userAuthenticators,
Integer userAuthenticationValidityDurationSeconds) {
if (context == null) { if (context == null) {
throw new IllegalArgumentException("context == null"); throw new IllegalArgumentException("context == null");
} else if (TextUtils.isEmpty(keyStoreAlias)) { } else if (TextUtils.isEmpty(keyStoreAlias)) {
@ -157,8 +148,8 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
throw new IllegalArgumentException("endDate == null"); throw new IllegalArgumentException("endDate == null");
} else if (endDate.before(startDate)) { } else if (endDate.before(startDate)) {
throw new IllegalArgumentException("endDate < startDate"); throw new IllegalArgumentException("endDate < startDate");
} else if ((userAuthenticationValidityDurationSeconds != null) } else if ((userAuthenticationValidityDurationSeconds < 0)
&& (userAuthenticationValidityDurationSeconds < 0)) { && (userAuthenticationValidityDurationSeconds != -1)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"userAuthenticationValidityDurationSeconds must not be negative"); "userAuthenticationValidityDurationSeconds must not be negative");
} }
@ -177,14 +168,10 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
mKeyValidityForOriginationEnd = keyValidityForOriginationEnd; mKeyValidityForOriginationEnd = keyValidityForOriginationEnd;
mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd; mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd;
mPurposes = purposes; mPurposes = purposes;
mDigest = digest; mDigests = digests;
mPadding = padding; mPaddings = paddings;
mBlockMode = blockMode; mBlockModes = blockModes;
mMinSecondsBetweenOperations = minSecondsBetweenOperations; mUserAuthenticators = userAuthenticators;
mMaxUsesPerBoot = maxUsesPerBoot;
mUserAuthenticators = (userAuthenticators != null)
? new HashSet<Integer>(userAuthenticators)
: Collections.<Integer>emptySet();
mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds; mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
} }
@ -196,8 +183,7 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
AlgorithmParameterSpec spec, X500Principal subjectDN, BigInteger serialNumber, AlgorithmParameterSpec spec, X500Principal subjectDN, BigInteger serialNumber,
Date startDate, Date endDate, int flags) { Date startDate, Date endDate, int flags) {
this(context, keyStoreAlias, keyType, keySize, spec, subjectDN, serialNumber, startDate, this(context, keyStoreAlias, keyType, keySize, spec, subjectDN, serialNumber, startDate,
endDate, flags, startDate, endDate, endDate, null, null, null, null, null, null, endDate, flags, startDate, endDate, endDate, 0, 0, 0, 0, 0, -1);
null, null);
} }
/** /**
@ -323,90 +309,52 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
/** /**
* Gets the set of purposes for which the key can be used. * Gets the set of purposes for which the key can be used.
* *
* @return set of purposes or {@code null} if the key can be used for any purpose.
*
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.PurposeEnum Integer getPurposes() { public @KeyStoreKeyConstraints.PurposeEnum int getPurposes() {
return mPurposes; return mPurposes;
} }
/** /**
* Gets the digest to which the key is restricted. * Gets the set of digests to which the key is restricted.
*
* @return digest or {@code null} if the digest is not restricted.
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.DigestEnum Integer getDigest() { public @KeyStoreKeyConstraints.DigestEnum int getDigests() {
return mDigest; return mDigests;
} }
/** /**
* Gets the padding scheme to which the key is restricted. * Gets the set of padding schemes to which the key is restricted.
*
* @return padding scheme or {@code null} if the padding scheme is not restricted.
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.PaddingEnum Integer getPadding() { public @KeyStoreKeyConstraints.PaddingEnum int getPaddings() {
return mPadding; return mPaddings;
} }
/** /**
* Gets the block mode to which the key is restricted when used for encryption or decryption. * Gets the set of block modes to which the key is restricted.
*
* @return block more or {@code null} if block mode is not restricted.
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.BlockModeEnum Integer getBlockMode() { public @KeyStoreKeyConstraints.BlockModeEnum int getBlockModes() {
return mBlockMode; return mBlockModes;
} }
/** /**
* Gets the minimum number of seconds that must expire since the most recent use of the private * Gets the set of user authenticators which protect access to the private key. The key can only
* key before it can be used again. * be used iff the user has authenticated to at least one of these user authenticators.
* *
* <p>This restriction applies only to private key operations. Public key operations are not * <p>This restriction applies only to private key operations. Public key operations are not
* restricted. * restricted.
* *
* @return number of seconds or {@code null} if there is no restriction on how frequently a key * @return user authenticators or {@code 0} if the key can be used without user authentication.
* can be used.
* *
* @hide * @hide
*/ */
public Integer getMinSecondsBetweenOperations() { public @KeyStoreKeyConstraints.UserAuthenticatorEnum int getUserAuthenticators() {
return mMinSecondsBetweenOperations; return mUserAuthenticators;
}
/**
* Gets the number of times the private key can be used without rebooting the device.
*
* <p>This restriction applies only to private key operations. Public key operations are not
* restricted.
*
* @return maximum number of times or {@code null} if there is no restriction.
*
* @hide
*/
public Integer getMaxUsesPerBoot() {
return mMaxUsesPerBoot;
}
/**
* Gets the user authenticators which protect access to the private key. The key can only be
* used iff the user has authenticated to at least one of these user authenticators.
*
* <p>This restriction applies only to private key operations. Public key operations are not
* restricted.
*
* @return user authenticators or empty set if the key can be used without user authentication.
*
* @hide
*/
public Set<Integer> getUserAuthenticators() {
return new HashSet<Integer>(mUserAuthenticators);
} }
/** /**
@ -416,12 +364,12 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
* <p>This restriction applies only to private key operations. Public key operations are not * <p>This restriction applies only to private key operations. Public key operations are not
* restricted. * restricted.
* *
* @return duration in seconds or {@code null} if not restricted. {@code 0} means authentication * @return duration in seconds or {@code -1} if not restricted. {@code 0} means authentication
* is required for every use of the key. * is required for every use of the key.
* *
* @hide * @hide
*/ */
public Integer getUserAuthenticationValidityDurationSeconds() { public int getUserAuthenticationValidityDurationSeconds() {
return mUserAuthenticationValidityDurationSeconds; return mUserAuthenticationValidityDurationSeconds;
} }
@ -473,21 +421,17 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
private Date mKeyValidityForConsumptionEnd; private Date mKeyValidityForConsumptionEnd;
private @KeyStoreKeyConstraints.PurposeEnum Integer mPurposes; private @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private @KeyStoreKeyConstraints.DigestEnum Integer mDigest; private @KeyStoreKeyConstraints.DigestEnum int mDigests;
private @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private Integer mMinSecondsBetweenOperations; private @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private Integer mMaxUsesPerBoot; private int mUserAuthenticationValidityDurationSeconds = -1;
private Set<Integer> mUserAuthenticators;
private Integer mUserAuthenticationValidityDurationSeconds;
/** /**
* Creates a new instance of the {@code Builder} with the given * Creates a new instance of the {@code Builder} with the given
@ -675,9 +619,9 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
} }
/** /**
* Restricts the purposes for which the key can be used to the provided set of purposes. * Restricts the key to being used only for the provided set of purposes.
* *
* <p>By default, the key can be used for encryption, decryption, signing, and verification. * <p>This restriction must be specified. There is no default.
* *
* @hide * @hide
*/ */
@ -687,28 +631,28 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
} }
/** /**
* Restricts the key to being used only with the provided digest. Attempts to use the key * Restricts the key to being used only with the provided digests. Attempts to use the key
* with any other digests be rejected. * with any other digests be rejected.
* *
* <p>This restriction must be specified for keys which are used for signing/verification. * <p>This restriction must be specified for keys which are used for signing/verification.
* *
* @hide * @hide
*/ */
public Builder setDigest(@KeyStoreKeyConstraints.DigestEnum int digest) { public Builder setDigests(@KeyStoreKeyConstraints.DigestEnum int digests) {
mDigest = digest; mDigests = digests;
return this; return this;
} }
/** /**
* Restricts the key to being used only with the provided padding scheme. Attempts to use * Restricts the key to being used only with the provided padding schemes. Attempts to use
* the key with any other padding will be rejected. * the key with any other padding will be rejected.
* *
* <p>This restriction must be specified for keys which are used for encryption/decryption. * <p>This restriction must be specified for keys which are used for encryption/decryption.
* *
* @hide * @hide
*/ */
public Builder setPadding(@KeyStoreKeyConstraints.PaddingEnum int padding) { public Builder setPaddings(@KeyStoreKeyConstraints.PaddingEnum int paddings) {
mPadding = padding; mPaddings = paddings;
return this; return this;
} }
@ -720,39 +664,8 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
* *
* @hide * @hide
*/ */
public Builder setBlockMode(@KeyStoreKeyConstraints.BlockModeEnum int blockMode) { public Builder setBlockModes(@KeyStoreKeyConstraints.BlockModeEnum int blockModes) {
mBlockMode = blockMode; mBlockModes = blockModes;
return this;
}
/**
* Sets the minimum number of seconds that must expire since the most recent use of the key
* before it can be used again.
*
* <p>By default, there is no restriction on how frequently a key can be used.
*
* <p>This restriction applies only to private key operations. Public key operations are not
* restricted.
*
* @hide
*/
public Builder setMinSecondsBetweenOperations(int seconds) {
mMinSecondsBetweenOperations = seconds;
return this;
}
/**
* Sets the maximum number of times a key can be used without rebooting the device.
*
* <p>By default, the key can be used for an unlimited number of times.
*
* <p>This restriction applies only to private key operations. Public key operations are not
* restricted.
*
* @hide
*/
public Builder setMaxUsesPerBoot(int count) {
mMaxUsesPerBoot = count;
return this; return this;
} }
@ -765,16 +678,16 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
* <p>This restriction applies only to private key operations. Public key operations are not * <p>This restriction applies only to private key operations. Public key operations are not
* restricted. * restricted.
* *
* @param userAuthenticators user authenticators or empty list if this key can be accessed * @param userAuthenticators user authenticators or {@code 0} if this key can be accessed
* without user authentication. * without user authentication.
* *
* @see #setUserAuthenticationValidityDurationSeconds(int) * @see #setUserAuthenticationValidityDurationSeconds(int)
* *
* @hide * @hide
*/ */
public Builder setUserAuthenticators(Set<Integer> userAuthenticators) { public Builder setUserAuthenticators(
mUserAuthenticators = @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators) {
(userAuthenticators != null) ? new HashSet<Integer>(userAuthenticators) : null; mUserAuthenticators = userAuthenticators;
return this; return this;
} }
@ -790,7 +703,7 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
* @param seconds duration in seconds or {@code 0} if the user needs to authenticate for * @param seconds duration in seconds or {@code 0} if the user needs to authenticate for
* every use of the key. * every use of the key.
* *
* @see #setUserAuthenticators(Set) * @see #setUserAuthenticators(int)
* *
* @hide * @hide
*/ */
@ -820,11 +733,9 @@ public final class KeyPairGeneratorSpec implements AlgorithmParameterSpec {
mKeyValidityForOriginationEnd, mKeyValidityForOriginationEnd,
mKeyValidityForConsumptionEnd, mKeyValidityForConsumptionEnd,
mPurposes, mPurposes,
mDigest, mDigests,
mPadding, mPaddings,
mBlockMode, mBlockModes,
mMinSecondsBetweenOperations,
mMaxUsesPerBoot,
mUserAuthenticators, mUserAuthenticators,
mUserAuthenticationValidityDurationSeconds); mUserAuthenticationValidityDurationSeconds);
} }

View File

@ -21,12 +21,8 @@ import android.security.keymaster.KeymasterDefs;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale; import java.util.Locale;
import java.util.Set;
/** /**
* Constraints for {@code AndroidKeyStore} keys. * Constraints for {@code AndroidKeyStore} keys.
@ -37,7 +33,8 @@ public abstract class KeyStoreKeyConstraints {
private KeyStoreKeyConstraints() {} private KeyStoreKeyConstraints() {}
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@IntDef(flag=true, value={Purpose.ENCRYPT, Purpose.DECRYPT, Purpose.SIGN, Purpose.VERIFY}) @IntDef(flag = true,
value = {Purpose.ENCRYPT, Purpose.DECRYPT, Purpose.SIGN, Purpose.VERIFY})
public @interface PurposeEnum {} public @interface PurposeEnum {}
/** /**
@ -66,11 +63,6 @@ public abstract class KeyStoreKeyConstraints {
*/ */
public static final int VERIFY = 1 << 3; public static final int VERIFY = 1 << 3;
/**
* Number of flags defined above. Needs to be kept in sync with the flags above.
*/
private static final int VALUE_COUNT = 4;
/** /**
* @hide * @hide
*/ */
@ -110,22 +102,12 @@ public abstract class KeyStoreKeyConstraints {
/** /**
* @hide * @hide
*/ */
public static int[] allToKeymaster(int purposes) { public static int[] allToKeymaster(@PurposeEnum int purposes) {
int[] result = new int[VALUE_COUNT]; int[] result = getSetFlags(purposes);
int resultCount = 0; for (int i = 0; i < result.length; i++) {
int purpose = 1; result[i] = toKeymaster(result[i]);
for (int i = 0; i < 32; i++) {
if ((purposes & 1) != 0) {
result[resultCount] = toKeymaster(purpose);
resultCount++;
}
purposes >>>= 1;
purpose <<= 1;
if (purposes == 0) {
break;
}
} }
return Arrays.copyOf(result, resultCount); return result;
} }
/** /**
@ -244,7 +226,8 @@ public abstract class KeyStoreKeyConstraints {
} }
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@IntDef({Padding.NONE, Padding.ZERO, Padding.PKCS7}) @IntDef(flag = true,
value = {Padding.NONE, Padding.PKCS7})
public @interface PaddingEnum {} public @interface PaddingEnum {}
/** /**
@ -256,17 +239,12 @@ public abstract class KeyStoreKeyConstraints {
/** /**
* No padding. * No padding.
*/ */
public static final int NONE = 0; public static final int NONE = 1 << 0;
/**
* Pad with zeros.
*/
public static final int ZERO = 1;
/** /**
* PKCS#7 padding. * PKCS#7 padding.
*/ */
public static final int PKCS7 = 2; public static final int PKCS7 = 1 << 1;
/** /**
* @hide * @hide
@ -275,8 +253,6 @@ public abstract class KeyStoreKeyConstraints {
switch (padding) { switch (padding) {
case NONE: case NONE:
return KeymasterDefs.KM_PAD_NONE; return KeymasterDefs.KM_PAD_NONE;
case ZERO:
return KeymasterDefs.KM_PAD_ZERO;
case PKCS7: case PKCS7:
return KeymasterDefs.KM_PAD_PKCS7; return KeymasterDefs.KM_PAD_PKCS7;
default: default:
@ -291,8 +267,6 @@ public abstract class KeyStoreKeyConstraints {
switch (padding) { switch (padding) {
case KeymasterDefs.KM_PAD_NONE: case KeymasterDefs.KM_PAD_NONE:
return NONE; return NONE;
case KeymasterDefs.KM_PAD_ZERO:
return ZERO;
case KeymasterDefs.KM_PAD_PKCS7: case KeymasterDefs.KM_PAD_PKCS7:
return PKCS7; return PKCS7;
default: default:
@ -307,8 +281,6 @@ public abstract class KeyStoreKeyConstraints {
switch (padding) { switch (padding) {
case NONE: case NONE:
return "NONE"; return "NONE";
case ZERO:
return "ZERO";
case PKCS7: case PKCS7:
return "PKCS#7"; return "PKCS#7";
default: default:
@ -329,10 +301,33 @@ public abstract class KeyStoreKeyConstraints {
throw new IllegalArgumentException("Unknown padding: " + padding); throw new IllegalArgumentException("Unknown padding: " + padding);
} }
} }
/**
* @hide
*/
public static int[] allToKeymaster(@PaddingEnum int paddings) {
int[] result = getSetFlags(paddings);
for (int i = 0; i < result.length; i++) {
result[i] = toKeymaster(result[i]);
}
return result;
}
/**
* @hide
*/
public static @PaddingEnum int allFromKeymaster(Collection<Integer> paddings) {
@PaddingEnum int result = 0;
for (int keymasterPadding : paddings) {
result |= fromKeymaster(keymasterPadding);
}
return result;
}
} }
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@IntDef({Digest.NONE, Digest.SHA256}) @IntDef(flag = true,
value = {Digest.NONE, Digest.SHA256})
public @interface DigestEnum {} public @interface DigestEnum {}
/** /**
@ -345,12 +340,12 @@ public abstract class KeyStoreKeyConstraints {
/** /**
* No digest: sign/authenticate the raw message. * No digest: sign/authenticate the raw message.
*/ */
public static final int NONE = 0; public static final int NONE = 1 << 0;
/** /**
* SHA-256 digest. * SHA-256 digest.
*/ */
public static final int SHA256 = 1; public static final int SHA256 = 1 << 1;
/** /**
* @hide * @hide
@ -366,6 +361,18 @@ public abstract class KeyStoreKeyConstraints {
} }
} }
/**
* @hide
*/
public static String[] allToString(@DigestEnum int digests) {
int[] values = getSetFlags(digests);
String[] result = new String[values.length];
for (int i = 0; i < values.length; i++) {
result[i] = toString(values[i]);
}
return result;
}
/** /**
* @hide * @hide
*/ */
@ -394,6 +401,28 @@ public abstract class KeyStoreKeyConstraints {
} }
} }
/**
* @hide
*/
public static int[] allToKeymaster(@DigestEnum int digests) {
int[] result = getSetFlags(digests);
for (int i = 0; i < result.length; i++) {
result[i] = toKeymaster(result[i]);
}
return result;
}
/**
* @hide
*/
public static @DigestEnum int allFromKeymaster(Collection<Integer> digests) {
@DigestEnum int result = 0;
for (int keymasterDigest : digests) {
result |= fromKeymaster(keymasterDigest);
}
return result;
}
/** /**
* @hide * @hide
*/ */
@ -441,7 +470,8 @@ public abstract class KeyStoreKeyConstraints {
} }
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@IntDef({BlockMode.ECB, BlockMode.CBC, BlockMode.CTR}) @IntDef(flag = true,
value = {BlockMode.ECB, BlockMode.CBC, BlockMode.CTR})
public @interface BlockModeEnum {} public @interface BlockModeEnum {}
/** /**
@ -451,13 +481,13 @@ public abstract class KeyStoreKeyConstraints {
private BlockMode() {} private BlockMode() {}
/** Electronic Codebook (ECB) block mode. */ /** Electronic Codebook (ECB) block mode. */
public static final int ECB = 0; public static final int ECB = 1 << 0;
/** Cipher Block Chaining (CBC) block mode. */ /** Cipher Block Chaining (CBC) block mode. */
public static final int CBC = 1; public static final int CBC = 1 << 1;
/** Counter (CTR) block mode. */ /** Counter (CTR) block mode. */
public static final int CTR = 2; public static final int CTR = 1 << 2;
/** /**
* @hide * @hide
@ -491,6 +521,28 @@ public abstract class KeyStoreKeyConstraints {
} }
} }
/**
* @hide
*/
public static int[] allToKeymaster(@BlockModeEnum int modes) {
int[] result = getSetFlags(modes);
for (int i = 0; i < result.length; i++) {
result[i] = toKeymaster(result[i]);
}
return result;
}
/**
* @hide
*/
public static @BlockModeEnum int allFromKeymaster(Collection<Integer> modes) {
@BlockModeEnum int result = 0;
for (int keymasterMode : modes) {
result |= fromKeymaster(keymasterMode);
}
return result;
}
/** /**
* @hide * @hide
*/ */
@ -525,7 +577,8 @@ public abstract class KeyStoreKeyConstraints {
} }
@Retention(RetentionPolicy.SOURCE) @Retention(RetentionPolicy.SOURCE)
@IntDef({UserAuthenticator.LOCK_SCREEN}) @IntDef(flag = true,
value = {UserAuthenticator.LOCK_SCREEN})
public @interface UserAuthenticatorEnum {} public @interface UserAuthenticatorEnum {}
/** /**
@ -535,7 +588,7 @@ public abstract class KeyStoreKeyConstraints {
private UserAuthenticator() {} private UserAuthenticator() {}
/** Lock screen. */ /** Lock screen. */
public static final int LOCK_SCREEN = 1; public static final int LOCK_SCREEN = 1 << 0;
/** /**
* @hide * @hide
@ -543,7 +596,7 @@ public abstract class KeyStoreKeyConstraints {
public static int toKeymaster(@UserAuthenticatorEnum int userAuthenticator) { public static int toKeymaster(@UserAuthenticatorEnum int userAuthenticator) {
switch (userAuthenticator) { switch (userAuthenticator) {
case LOCK_SCREEN: case LOCK_SCREEN:
return LOCK_SCREEN; return KeymasterDefs.HW_AUTH_PASSWORD;
default: default:
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Unknown user authenticator: " + userAuthenticator); "Unknown user authenticator: " + userAuthenticator);
@ -555,7 +608,7 @@ public abstract class KeyStoreKeyConstraints {
*/ */
public static @UserAuthenticatorEnum int fromKeymaster(int userAuthenticator) { public static @UserAuthenticatorEnum int fromKeymaster(int userAuthenticator) {
switch (userAuthenticator) { switch (userAuthenticator) {
case LOCK_SCREEN: case KeymasterDefs.HW_AUTH_PASSWORD:
return LOCK_SCREEN; return LOCK_SCREEN;
default: default:
throw new IllegalArgumentException( throw new IllegalArgumentException(
@ -566,10 +619,15 @@ public abstract class KeyStoreKeyConstraints {
/** /**
* @hide * @hide
*/ */
public static int allToKeymaster(Set<Integer> userAuthenticators) { public static int allToKeymaster(@UserAuthenticatorEnum int userAuthenticators) {
int result = 0; int result = 0;
for (@UserAuthenticatorEnum int userAuthenticator : userAuthenticators) { int userAuthenticator = 1;
result |= toKeymaster(userAuthenticator); while (userAuthenticators != 0) {
if ((userAuthenticators & 1) != 0) {
result |= toKeymaster(userAuthenticator);
}
userAuthenticators >>>= 1;
userAuthenticator <<= 1;
} }
return result; return result;
} }
@ -577,20 +635,17 @@ public abstract class KeyStoreKeyConstraints {
/** /**
* @hide * @hide
*/ */
public static Set<Integer> allFromKeymaster(int userAuthenticators) { public static @UserAuthenticatorEnum int allFromKeymaster(int userAuthenticators) {
@UserAuthenticatorEnum int result = 0;
int userAuthenticator = 1; int userAuthenticator = 1;
Set<Integer> result = null;
while (userAuthenticators != 0) { while (userAuthenticators != 0) {
if ((userAuthenticators & 1) != 0) { if ((userAuthenticators & 1) != 0) {
if (result == null) { result |= fromKeymaster(userAuthenticator);
result = new HashSet<Integer>();
}
result.add(fromKeymaster(userAuthenticator));
} }
userAuthenticators >>>= 1; userAuthenticators >>>= 1;
userAuthenticator <<= 1; userAuthenticator <<= 1;
} }
return (result != null) ? result : Collections.<Integer>emptySet(); return result;
} }
/** /**
@ -606,4 +661,38 @@ public abstract class KeyStoreKeyConstraints {
} }
} }
} }
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static int[] getSetFlags(int flags) {
if (flags == 0) {
return EMPTY_INT_ARRAY;
}
int result[] = new int[getSetBitCount(flags)];
int resultOffset = 0;
int flag = 1;
while (flags != 0) {
if ((flags & 1) != 0) {
result[resultOffset] = flag;
resultOffset++;
}
flags >>>= 1;
flag <<= 1;
}
return result;
}
private static int getSetBitCount(int value) {
if (value == 0) {
return 0;
}
int result = 0;
while (value != 0) {
if ((value & 1) != 0) {
result++;
}
value >>>= 1;
}
return result;
}
} }

View File

@ -109,39 +109,27 @@ public abstract class KeyStoreKeyGeneratorSpi extends KeyGeneratorSpi {
} }
int keySizeBits = (spec.getKeySize() != null) ? spec.getKeySize() : mDefaultKeySizeBits; int keySizeBits = (spec.getKeySize() != null) ? spec.getKeySize() : mDefaultKeySizeBits;
args.addInt(KeymasterDefs.KM_TAG_KEY_SIZE, keySizeBits); args.addInt(KeymasterDefs.KM_TAG_KEY_SIZE, keySizeBits);
@KeyStoreKeyConstraints.PurposeEnum int purposes = (spec.getPurposes() != null) int purposes = spec.getPurposes();
? spec.getPurposes()
: (KeyStoreKeyConstraints.Purpose.ENCRYPT
| KeyStoreKeyConstraints.Purpose.DECRYPT
| KeyStoreKeyConstraints.Purpose.SIGN
| KeyStoreKeyConstraints.Purpose.VERIFY);
for (int keymasterPurpose : for (int keymasterPurpose :
KeyStoreKeyConstraints.Purpose.allToKeymaster(purposes)) { KeyStoreKeyConstraints.Purpose.allToKeymaster(purposes)) {
args.addInt(KeymasterDefs.KM_TAG_PURPOSE, keymasterPurpose); args.addInt(KeymasterDefs.KM_TAG_PURPOSE, keymasterPurpose);
} }
if (spec.getBlockMode() != null) { for (int keymasterBlockMode :
args.addInt(KeymasterDefs.KM_TAG_BLOCK_MODE, KeyStoreKeyConstraints.BlockMode.allToKeymaster(spec.getBlockModes())) {
KeyStoreKeyConstraints.BlockMode.toKeymaster(spec.getBlockMode())); args.addInt(KeymasterDefs.KM_TAG_BLOCK_MODE, keymasterBlockMode);
} }
if (spec.getPadding() != null) { for (int keymasterPadding :
args.addInt(KeymasterDefs.KM_TAG_PADDING, KeyStoreKeyConstraints.Padding.allToKeymaster(spec.getPaddings())) {
KeyStoreKeyConstraints.Padding.toKeymaster(spec.getPadding())); args.addInt(KeymasterDefs.KM_TAG_PADDING, keymasterPadding);
} }
if (spec.getMaxUsesPerBoot() != null) { if (spec.getUserAuthenticators() == 0) {
args.addInt(KeymasterDefs.KM_TAG_MAX_USES_PER_BOOT, spec.getMaxUsesPerBoot());
}
if (spec.getMinSecondsBetweenOperations() != null) {
args.addInt(KeymasterDefs.KM_TAG_MIN_SECONDS_BETWEEN_OPS,
spec.getMinSecondsBetweenOperations());
}
if (spec.getUserAuthenticators().isEmpty()) {
args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED); args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
} else { } else {
args.addInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, args.addInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE,
KeyStoreKeyConstraints.UserAuthenticator.allToKeymaster( KeyStoreKeyConstraints.UserAuthenticator.allToKeymaster(
spec.getUserAuthenticators())); spec.getUserAuthenticators()));
} }
if (spec.getUserAuthenticationValidityDurationSeconds() != null) { if (spec.getUserAuthenticationValidityDurationSeconds() != -1) {
args.addInt(KeymasterDefs.KM_TAG_AUTH_TIMEOUT, args.addInt(KeymasterDefs.KM_TAG_AUTH_TIMEOUT,
spec.getUserAuthenticationValidityDurationSeconds()); spec.getUserAuthenticationValidityDurationSeconds());
} }

View File

@ -17,10 +17,7 @@
package android.security; package android.security;
import java.security.spec.KeySpec; import java.security.spec.KeySpec;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/** /**
* Information about a key from the <a href="{@docRoot}training/articles/keystore.html">Android * Information about a key from the <a href="{@docRoot}training/articles/keystore.html">Android
@ -37,14 +34,12 @@ public class KeyStoreKeySpec implements KeySpec {
private final Date mKeyValidityForConsumptionEnd; private final Date mKeyValidityForConsumptionEnd;
private final @KeyStoreKeyConstraints.PurposeEnum int mPurposes; private final @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private final @KeyStoreKeyConstraints.AlgorithmEnum int mAlgorithm; private final @KeyStoreKeyConstraints.AlgorithmEnum int mAlgorithm;
private final @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private final @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private final @KeyStoreKeyConstraints.DigestEnum Integer mDigest; private final @KeyStoreKeyConstraints.DigestEnum int mDigests;
private final @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private final @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private final Integer mMinSecondsBetweenOperations; private final @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private final Integer mMaxUsesPerBoot; private final @KeyStoreKeyConstraints.UserAuthenticatorEnum int mTeeEnforcedUserAuthenticators;
private final Set<Integer> mUserAuthenticators; private final int mUserAuthenticationValidityDurationSeconds;
private final Set<Integer> mTeeBackedUserAuthenticators;
private final Integer mUserAuthenticationValidityDurationSeconds;
/** /**
@ -52,18 +47,18 @@ public class KeyStoreKeySpec implements KeySpec {
*/ */
KeyStoreKeySpec(String keystoreKeyAlias, KeyStoreKeySpec(String keystoreKeyAlias,
@KeyStoreKeyCharacteristics.OriginEnum int origin, @KeyStoreKeyCharacteristics.OriginEnum int origin,
int keySize, Date keyValidityStart, Date keyValidityForOriginationEnd, int keySize,
Date keyValidityStart,
Date keyValidityForOriginationEnd,
Date keyValidityForConsumptionEnd, Date keyValidityForConsumptionEnd,
@KeyStoreKeyConstraints.PurposeEnum int purposes, @KeyStoreKeyConstraints.PurposeEnum int purposes,
@KeyStoreKeyConstraints.AlgorithmEnum int algorithm, @KeyStoreKeyConstraints.AlgorithmEnum int algorithm,
@KeyStoreKeyConstraints.PaddingEnum Integer padding, @KeyStoreKeyConstraints.PaddingEnum int paddings,
@KeyStoreKeyConstraints.DigestEnum Integer digest, @KeyStoreKeyConstraints.DigestEnum int digests,
@KeyStoreKeyConstraints.BlockModeEnum Integer blockMode, @KeyStoreKeyConstraints.BlockModeEnum int blockModes,
Integer minSecondsBetweenOperations, @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators,
Integer maxUsesPerBoot, @KeyStoreKeyConstraints.UserAuthenticatorEnum int teeEnforcedUserAuthenticators,
Set<Integer> userAuthenticators, int userAuthenticationValidityDurationSeconds) {
Set<Integer> teeBackedUserAuthenticators,
Integer userAuthenticationValidityDurationSeconds) {
mKeystoreAlias = keystoreKeyAlias; mKeystoreAlias = keystoreKeyAlias;
mOrigin = origin; mOrigin = origin;
mKeySize = keySize; mKeySize = keySize;
@ -72,17 +67,11 @@ public class KeyStoreKeySpec implements KeySpec {
mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd; mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd;
mPurposes = purposes; mPurposes = purposes;
mAlgorithm = algorithm; mAlgorithm = algorithm;
mPadding = padding; mPaddings = paddings;
mDigest = digest; mDigests = digests;
mBlockMode = blockMode; mBlockModes = blockModes;
mMinSecondsBetweenOperations = minSecondsBetweenOperations; mUserAuthenticators = userAuthenticators;
mMaxUsesPerBoot = maxUsesPerBoot; mTeeEnforcedUserAuthenticators = teeEnforcedUserAuthenticators;
mUserAuthenticators = (userAuthenticators != null)
? new HashSet<Integer>(userAuthenticators)
: Collections.<Integer>emptySet();
mTeeBackedUserAuthenticators = (teeBackedUserAuthenticators != null)
? new HashSet<Integer>(teeBackedUserAuthenticators)
: Collections.<Integer>emptySet();
mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds; mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
} }
@ -101,7 +90,7 @@ public class KeyStoreKeySpec implements KeySpec {
} }
/** /**
* Gets the key's size in bits. * Gets the size of the key in bits.
*/ */
public int getKeySize() { public int getKeySize() {
return mKeySize; return mKeySize;
@ -149,78 +138,53 @@ public class KeyStoreKeySpec implements KeySpec {
} }
/** /**
* Gets the only block mode with which the key can be used. * Gets the set of block modes with which the key can be used.
*
* @return block mode or {@code null} if the block mode is not restricted.
*/ */
public @KeyStoreKeyConstraints.BlockModeEnum Integer getBlockMode() { public @KeyStoreKeyConstraints.BlockModeEnum int getBlockModes() {
return mBlockMode; return mBlockModes;
} }
/** /**
* Gets the only padding mode with which the key can be used. * Gets the set of padding modes with which the key can be used.
*
* @return padding mode or {@code null} if the padding mode is not restricted.
*/ */
public @KeyStoreKeyConstraints.PaddingEnum Integer getPadding() { public @KeyStoreKeyConstraints.PaddingEnum int getPaddings() {
return mPadding; return mPaddings;
} }
/** /**
* Gets the only digest algorithm with which the key can be used. * Gets the set of digest algorithms with which the key can be used.
*
* @return digest algorithm or {@code null} if the digest algorithm is not restricted.
*/ */
public @KeyStoreKeyConstraints.DigestEnum Integer getDigest() { public @KeyStoreKeyConstraints.DigestEnum int getDigests() {
return mDigest; return mDigests;
} }
/** /**
* Gets the minimum number of seconds that must expire since the most recent use of the key * Gets the set of user authenticators which protect access to the key. The key can only be used
* before it can be used again. * iff the user has authenticated to at least one of these user authenticators.
* *
* @return number of seconds or {@code null} if there is no restriction on how frequently a key * @return user authenticators or {@code 0} if the key can be used without user authentication.
* can be used.
*/ */
public Integer getMinSecondsBetweenOperations() { public @KeyStoreKeyConstraints.UserAuthenticatorEnum int getUserAuthenticators() {
return mMinSecondsBetweenOperations; return mUserAuthenticators;
} }
/** /**
* Gets the number of times the key can be used without rebooting the device. * Gets the set of user authenticators for which the TEE enforces access restrictions for this
* * key. This is a subset of the user authentications returned by
* @return maximum number of times or {@code null} if there is no restriction. * {@link #getUserAuthenticators()}.
*/ */
public Integer getMaxUsesPerBoot() { public @KeyStoreKeyConstraints.UserAuthenticatorEnum int getTeeEnforcedUserAuthenticators() {
return mMaxUsesPerBoot; return mTeeEnforcedUserAuthenticators;
}
/**
* Gets the user authenticators which protect access to the key. The key can only be used iff
* the user has authenticated to at least one of these user authenticators.
*
* @return user authenticators or empty set if the key can be used without user authentication.
*/
public Set<Integer> getUserAuthenticators() {
return new HashSet<Integer>(mUserAuthenticators);
}
/**
* Gets the TEE-backed user authenticators which protect access to the key. This is a subset of
* the user authentications returned by {@link #getUserAuthenticators()}.
*/
public Set<Integer> getTeeBackedUserAuthenticators() {
return new HashSet<Integer>(mTeeBackedUserAuthenticators);
} }
/** /**
* Gets the duration of time (seconds) for which the key can be used after the user * Gets the duration of time (seconds) for which the key can be used after the user
* successfully authenticates to one of the associated user authenticators. * successfully authenticates to one of the associated user authenticators.
* *
* @return duration in seconds or {@code null} if not restricted. {@code 0} means authentication * @return duration in seconds or {@code -1} if not restricted. {@code 0} means authentication
* is required for every use of the key. * is required for every use of the key.
*/ */
public Integer getUserAuthenticationValidityDurationSeconds() { public int getUserAuthenticationValidityDurationSeconds() {
return mUserAuthenticationValidityDurationSeconds; return mUserAuthenticationValidityDurationSeconds;
} }
} }

View File

@ -18,12 +18,10 @@ package android.security;
import android.content.Context; import android.content.Context;
import java.security.Key;
import java.security.KeyPairGenerator; import java.security.KeyPairGenerator;
import java.security.KeyStore.ProtectionParameter; import java.security.KeyStore.ProtectionParameter;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/** /**
* This provides the optional parameters that can be specified for * This provides the optional parameters that can be specified for
@ -50,31 +48,25 @@ public final class KeyStoreParameter implements ProtectionParameter {
private final Date mKeyValidityStart; private final Date mKeyValidityStart;
private final Date mKeyValidityForOriginationEnd; private final Date mKeyValidityForOriginationEnd;
private final Date mKeyValidityForConsumptionEnd; private final Date mKeyValidityForConsumptionEnd;
private final @KeyStoreKeyConstraints.PurposeEnum Integer mPurposes; private final @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private final @KeyStoreKeyConstraints.AlgorithmEnum Integer mAlgorithm; private final @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private final @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private final @KeyStoreKeyConstraints.DigestEnum Integer mDigests;
private final @KeyStoreKeyConstraints.DigestEnum Integer mDigest; private final @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private final @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private final @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private final Integer mMinSecondsBetweenOperations; private final int mUserAuthenticationValidityDurationSeconds;
private final Integer mMaxUsesPerBoot;
private final Set<Integer> mUserAuthenticators;
private final Integer mUserAuthenticationValidityDurationSeconds;
private KeyStoreParameter(int flags, private KeyStoreParameter(int flags,
Date keyValidityStart, Date keyValidityStart,
Date keyValidityForOriginationEnd, Date keyValidityForOriginationEnd,
Date keyValidityForConsumptionEnd, Date keyValidityForConsumptionEnd,
@KeyStoreKeyConstraints.PurposeEnum Integer purposes, @KeyStoreKeyConstraints.PurposeEnum int purposes,
@KeyStoreKeyConstraints.AlgorithmEnum Integer algorithm, @KeyStoreKeyConstraints.PaddingEnum int paddings,
@KeyStoreKeyConstraints.PaddingEnum Integer padding, @KeyStoreKeyConstraints.DigestEnum Integer digests,
@KeyStoreKeyConstraints.DigestEnum Integer digest, @KeyStoreKeyConstraints.BlockModeEnum int blockModes,
@KeyStoreKeyConstraints.BlockModeEnum Integer blockMode, @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators,
Integer minSecondsBetweenOperations, int userAuthenticationValidityDurationSeconds) {
Integer maxUsesPerBoot, if ((userAuthenticationValidityDurationSeconds < 0)
Set<Integer> userAuthenticators, && (userAuthenticationValidityDurationSeconds != -1)) {
Integer userAuthenticationValidityDurationSeconds) {
if ((userAuthenticationValidityDurationSeconds != null)
&& (userAuthenticationValidityDurationSeconds < 0)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"userAuthenticationValidityDurationSeconds must not be negative"); "userAuthenticationValidityDurationSeconds must not be negative");
} }
@ -84,15 +76,10 @@ public final class KeyStoreParameter implements ProtectionParameter {
mKeyValidityForOriginationEnd = keyValidityForOriginationEnd; mKeyValidityForOriginationEnd = keyValidityForOriginationEnd;
mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd; mKeyValidityForConsumptionEnd = keyValidityForConsumptionEnd;
mPurposes = purposes; mPurposes = purposes;
mAlgorithm = algorithm; mPaddings = paddings;
mPadding = padding; mDigests = digests;
mDigest = digest; mBlockModes = blockModes;
mBlockMode = blockMode; mUserAuthenticators = userAuthenticators;
mMinSecondsBetweenOperations = minSecondsBetweenOperations;
mMaxUsesPerBoot = maxUsesPerBoot;
mUserAuthenticators = (userAuthenticators != null)
? new HashSet<Integer>(userAuthenticators)
: Collections.<Integer>emptySet();
mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds; mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
} }
@ -144,105 +131,81 @@ public final class KeyStoreParameter implements ProtectionParameter {
} }
/** /**
* Gets the set of purposes for which the key can be used to the provided set of purposes. * Gets the set of purposes for which the key can be used.
*
* @return set of purposes or {@code null} if the key can be used for any purpose.
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.PurposeEnum Integer getPurposes() { public @KeyStoreKeyConstraints.PurposeEnum int getPurposes() {
return mPurposes; return mPurposes;
} }
/** /**
* Gets the algorithm to which the key is restricted. * Gets the set of padding schemes to which the key is restricted.
* *
* @return algorithm or {@code null} if it's not restricted.
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.AlgorithmEnum Integer getAlgorithm() { public @KeyStoreKeyConstraints.PaddingEnum int getPaddings() {
return mAlgorithm; return mPaddings;
} }
/** /**
* Gets the padding scheme to which the key is restricted. * Gets the set of digests to which the key is restricted.
* *
* @return padding scheme or {@code null} if the padding scheme is not restricted. * @throws IllegalStateException if this restriction has not been specified.
*
* @see #isDigestsSpecified()
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.PaddingEnum Integer getPadding() { public @KeyStoreKeyConstraints.DigestEnum int getDigests() {
return mPadding; if (mDigests == null) {
throw new IllegalStateException("Digests not specified");
}
return mDigests;
} }
/** /**
* Gets the digest to which the key is restricted when generating signatures or Message * Returns {@code true} if digest restrictions have been specified.
* Authentication Codes (MACs).
* *
* @return digest or {@code null} if the digest is not restricted. * @see #getDigests()
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.DigestEnum Integer getDigest() { public boolean isDigestsSpecified() {
return mDigest; return mDigests != null;
} }
/** /**
* Gets the block mode to which the key is restricted when used for encryption or decryption. * Gets the set of block modes to which the key is restricted.
*
* @return block more or {@code null} if block mode is not restricted.
* *
* @hide * @hide
*/ */
public @KeyStoreKeyConstraints.BlockModeEnum Integer getBlockMode() { public @KeyStoreKeyConstraints.BlockModeEnum int getBlockModes() {
return mBlockMode; return mBlockModes;
} }
/** /**
* Gets the minimum number of seconds that must expire since the most recent use of the key * Gets the set of user authenticators which protect access to this key. The key can only be
* before it can be used again. * used iff the user has authenticated to at least one of these user authenticators.
* *
* @return number of seconds or {@code null} if there is no restriction on how frequently a key * @return user authenticators or {@code 0} if the key can be used without user authentication.
* can be used.
* *
* @hide * @hide
*/ */
public Integer getMinSecondsBetweenOperations() { public @KeyStoreKeyConstraints.UserAuthenticatorEnum int getUserAuthenticators() {
return mMinSecondsBetweenOperations; return mUserAuthenticators;
}
/**
* Gets the number of times the key can be used without rebooting the device.
*
* @return maximum number of times or {@code null} if there is no restriction.
* @hide
*/
public Integer getMaxUsesPerBoot() {
return mMaxUsesPerBoot;
}
/**
* Gets the user authenticators which protect access to this key. The key can only be used iff
* the user has authenticated to at least one of these user authenticators.
*
* @return user authenticators or empty set if the key can be used without user authentication.
*
* @hide
*/
public Set<Integer> getUserAuthenticators() {
return new HashSet<Integer>(mUserAuthenticators);
} }
/** /**
* Gets the duration of time (seconds) for which this key can be used after the user * Gets the duration of time (seconds) for which this key can be used after the user
* successfully authenticates to one of the associated user authenticators. * successfully authenticates to one of the associated user authenticators.
* *
* @return duration in seconds or {@code null} if not restricted. {@code 0} means authentication * @return duration in seconds or {@code -1} if not restricted. {@code 0} means authentication
* is required for every use of the key. * is required for every use of the key.
* *
* @hide * @hide
*/ */
public Integer getUserAuthenticationValidityDurationSeconds() { public int getUserAuthenticationValidityDurationSeconds() {
return mUserAuthenticationValidityDurationSeconds; return mUserAuthenticationValidityDurationSeconds;
} }
@ -268,15 +231,12 @@ public final class KeyStoreParameter implements ProtectionParameter {
private Date mKeyValidityStart; private Date mKeyValidityStart;
private Date mKeyValidityForOriginationEnd; private Date mKeyValidityForOriginationEnd;
private Date mKeyValidityForConsumptionEnd; private Date mKeyValidityForConsumptionEnd;
private @KeyStoreKeyConstraints.PurposeEnum Integer mPurposes; private @KeyStoreKeyConstraints.PurposeEnum int mPurposes;
private @KeyStoreKeyConstraints.AlgorithmEnum Integer mAlgorithm; private @KeyStoreKeyConstraints.PaddingEnum int mPaddings;
private @KeyStoreKeyConstraints.PaddingEnum Integer mPadding; private @KeyStoreKeyConstraints.DigestEnum Integer mDigests;
private @KeyStoreKeyConstraints.DigestEnum Integer mDigest; private @KeyStoreKeyConstraints.BlockModeEnum int mBlockModes;
private @KeyStoreKeyConstraints.BlockModeEnum Integer mBlockMode; private @KeyStoreKeyConstraints.UserAuthenticatorEnum int mUserAuthenticators;
private Integer mMinSecondsBetweenOperations; private int mUserAuthenticationValidityDurationSeconds = -1;
private Integer mMaxUsesPerBoot;
private Set<Integer> mUserAuthenticators;
private Integer mUserAuthenticationValidityDurationSeconds;
/** /**
* Creates a new instance of the {@code Builder} with the given * Creates a new instance of the {@code Builder} with the given
@ -368,9 +328,9 @@ public final class KeyStoreParameter implements ProtectionParameter {
} }
/** /**
* Restricts the purposes for which the key can be used to the provided set of purposes. * Restricts the key to being used only for the provided set of purposes.
* *
* <p>By default, the key can be used for encryption, decryption, signing, and verification. * <p>This restriction must be specified. There is no default.
* *
* @hide * @hide
*/ */
@ -380,84 +340,43 @@ public final class KeyStoreParameter implements ProtectionParameter {
} }
/** /**
* Sets the algorithm of the key. * Restricts the key to being used only with the provided padding schemes. Attempts to use
*
* <p>The algorithm of symmetric keys can be deduced from the key itself. Thus, explicitly
* specifying the algorithm of symmetric keys using this method is not necessary.
*
* @hide
*/
public Builder setAlgorithm(@KeyStoreKeyConstraints.AlgorithmEnum int algorithm) {
mAlgorithm = algorithm;
return this;
}
/**
* Restricts the key to being used only with the provided padding scheme. Attempts to use
* the key with any other padding will be rejected. * the key with any other padding will be rejected.
* *
* <p>This restriction must be specified for keys which are used for encryption/decryption. * <p>This restriction must be specified for keys which are used for encryption/decryption.
* *
* @hide * @hide
*/ */
public Builder setPadding(@KeyStoreKeyConstraints.PaddingEnum int padding) { public Builder setPaddings(@KeyStoreKeyConstraints.PaddingEnum int paddings) {
mPadding = padding; mPaddings = paddings;
return this; return this;
} }
/** /**
* Restricts the key to being used only with the provided digest when generating signatures * Restricts the key to being used only with the provided digests when generating signatures
* or Message Authentication Codes (MACs). Attempts to use the key with any other digest * or HMACs. Attempts to use the key with any other digest will be rejected.
* will be rejected.
* *
* <p>For MAC keys, the default is to restrict to the digest specified in the key algorithm * <p>For HMAC keys, the default is to restrict to the digest specified in
* name. For asymmetric signing keys this constraint must be specified because there is no * {@link Key#getAlgorithm()}. For asymmetric signing keys this constraint must be specified
* default. * because there is no default.
*
* @see java.security.Key#getAlgorithm()
* *
* @hide * @hide
*/ */
public Builder setDigest(@KeyStoreKeyConstraints.DigestEnum int digest) { public Builder setDigests(@KeyStoreKeyConstraints.DigestEnum int digests) {
mDigest = digest; mDigests = digests;
return this; return this;
} }
/** /**
* Restricts the key to being used only with the provided block mode when encrypting or * Restricts the key to being used only with the provided block modes. Attempts to use the
* decrypting. Attempts to use the key with any other block modes will be rejected. * key with any other block modes will be rejected.
* *
* <p>This restriction must be specified for keys which are used for encryption/decryption. * <p>This restriction must be specified for symmetric encryption/decryption keys.
* *
* @hide * @hide
*/ */
public Builder setBlockMode(@KeyStoreKeyConstraints.BlockModeEnum int blockMode) { public Builder setBlockModes(@KeyStoreKeyConstraints.BlockModeEnum int blockModes) {
mBlockMode = blockMode; mBlockModes = blockModes;
return this;
}
/**
* Sets the minimum number of seconds that must expire since the most recent use of the key
* before it can be used again.
*
* <p>By default, there is no restriction on how frequently a key can be used.
*
* @hide
*/
public Builder setMinSecondsBetweenOperations(int seconds) {
mMinSecondsBetweenOperations = seconds;
return this;
}
/**
* Sets the maximum number of times a key can be used without rebooting the device.
*
* <p>By default, the key can be used for an unlimited number of times.
*
* @hide
*/
public Builder setMaxUsesPerBoot(int count) {
mMaxUsesPerBoot = count;
return this; return this;
} }
@ -467,16 +386,16 @@ public final class KeyStoreParameter implements ProtectionParameter {
* *
* <p>By default, the key can be used without user authentication. * <p>By default, the key can be used without user authentication.
* *
* @param userAuthenticators user authenticators or empty list if this key can be accessed * @param userAuthenticators user authenticators or {@code 0} if this key can be accessed
* without user authentication. * without user authentication.
* *
* @see #setUserAuthenticationValidityDurationSeconds(int) * @see #setUserAuthenticationValidityDurationSeconds(int)
* *
* @hide * @hide
*/ */
public Builder setUserAuthenticators(Set<Integer> userAuthenticators) { public Builder setUserAuthenticators(
mUserAuthenticators = @KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators) {
(userAuthenticators != null) ? new HashSet<Integer>(userAuthenticators) : null; mUserAuthenticators = userAuthenticators;
return this; return this;
} }
@ -489,7 +408,7 @@ public final class KeyStoreParameter implements ProtectionParameter {
* @param seconds duration in seconds or {@code 0} if the user needs to authenticate for * @param seconds duration in seconds or {@code 0} if the user needs to authenticate for
* every use of the key. * every use of the key.
* *
* @see #setUserAuthenticators(Set) * @see #setUserAuthenticators(int)
* *
* @hide * @hide
*/ */
@ -510,12 +429,9 @@ public final class KeyStoreParameter implements ProtectionParameter {
mKeyValidityForOriginationEnd, mKeyValidityForOriginationEnd,
mKeyValidityForConsumptionEnd, mKeyValidityForConsumptionEnd,
mPurposes, mPurposes,
mAlgorithm, mPaddings,
mPadding, mDigests,
mDigest, mBlockModes,
mBlockMode,
mMinSecondsBetweenOperations,
mMaxUsesPerBoot,
mUserAuthenticators, mUserAuthenticators,
mUserAuthenticationValidityDurationSeconds); mUserAuthenticationValidityDurationSeconds);
} }

View File

@ -23,7 +23,6 @@ import java.security.InvalidKeyException;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec; import java.security.spec.KeySpec;
import java.util.Date; import java.util.Date;
import java.util.Set;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactorySpi; import javax.crypto.SecretKeyFactorySpi;
@ -75,9 +74,11 @@ public class KeyStoreSecretKeyFactorySpi extends SecretKeyFactorySpi {
int keySize; int keySize;
@KeyStoreKeyConstraints.PurposeEnum int purposes; @KeyStoreKeyConstraints.PurposeEnum int purposes;
@KeyStoreKeyConstraints.AlgorithmEnum int algorithm; @KeyStoreKeyConstraints.AlgorithmEnum int algorithm;
@KeyStoreKeyConstraints.PaddingEnum Integer padding; @KeyStoreKeyConstraints.PaddingEnum int paddings;
@KeyStoreKeyConstraints.DigestEnum Integer digest; @KeyStoreKeyConstraints.DigestEnum int digests;
@KeyStoreKeyConstraints.BlockModeEnum Integer blockMode; @KeyStoreKeyConstraints.BlockModeEnum int blockModes;
@KeyStoreKeyConstraints.UserAuthenticatorEnum int userAuthenticators;
@KeyStoreKeyConstraints.UserAuthenticatorEnum int teeEnforcedUserAuthenticators;
try { try {
origin = KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_ORIGIN); origin = KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_ORIGIN);
if (origin == null) { if (origin == null) {
@ -97,18 +98,27 @@ public class KeyStoreSecretKeyFactorySpi extends SecretKeyFactorySpi {
throw new InvalidKeySpecException("Key algorithm not available"); throw new InvalidKeySpecException("Key algorithm not available");
} }
algorithm = KeyStoreKeyConstraints.Algorithm.fromKeymaster(alg); algorithm = KeyStoreKeyConstraints.Algorithm.fromKeymaster(alg);
padding = KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_PADDING); paddings = KeyStoreKeyConstraints.Padding.allFromKeymaster(
if (padding != null) { KeymasterUtils.getInts(keyCharacteristics, KeymasterDefs.KM_TAG_PADDING));
padding = KeyStoreKeyConstraints.Padding.fromKeymaster(padding); digests = KeyStoreKeyConstraints.Digest.allFromKeymaster(
} KeymasterUtils.getInts(keyCharacteristics, KeymasterDefs.KM_TAG_DIGEST));
digest = KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_DIGEST); blockModes = KeyStoreKeyConstraints.BlockMode.allFromKeymaster(
if (digest != null) { KeymasterUtils.getInts(keyCharacteristics, KeymasterDefs.KM_TAG_BLOCK_MODE));
digest = KeyStoreKeyConstraints.Digest.fromKeymaster(digest);
} @KeyStoreKeyConstraints.UserAuthenticatorEnum
blockMode = KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_BLOCK_MODE); int swEnforcedKeymasterUserAuthenticators =
if (blockMode != null) { keyCharacteristics.swEnforced.getInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, 0);
blockMode = KeyStoreKeyConstraints.BlockMode.fromKeymaster(blockMode); @KeyStoreKeyConstraints.UserAuthenticatorEnum
} int hwEnforcedKeymasterUserAuthenticators =
keyCharacteristics.hwEnforced.getInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, 0);
@KeyStoreKeyConstraints.UserAuthenticatorEnum
int keymasterUserAuthenticators =
swEnforcedKeymasterUserAuthenticators | hwEnforcedKeymasterUserAuthenticators;
userAuthenticators = KeyStoreKeyConstraints.UserAuthenticator.allFromKeymaster(
keymasterUserAuthenticators);
teeEnforcedUserAuthenticators =
KeyStoreKeyConstraints.UserAuthenticator.allFromKeymaster(
hwEnforcedKeymasterUserAuthenticators);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new InvalidKeySpecException("Unsupported key characteristic", e); throw new InvalidKeySpecException("Unsupported key characteristic", e);
} }
@ -130,17 +140,8 @@ public class KeyStoreSecretKeyFactorySpi extends SecretKeyFactorySpi {
&& (keyValidityForConsumptionEnd.getTime() == Long.MAX_VALUE)) { && (keyValidityForConsumptionEnd.getTime() == Long.MAX_VALUE)) {
keyValidityForConsumptionEnd = null; keyValidityForConsumptionEnd = null;
} }
Integer userAuthenticationValidityDurationSeconds =
int swEnforcedUserAuthenticatorIds = KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_AUTH_TIMEOUT);
keyCharacteristics.swEnforced.getInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, 0);
int hwEnforcedUserAuthenticatorIds =
keyCharacteristics.hwEnforced.getInt(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, 0);
int userAuthenticatorIds = swEnforcedUserAuthenticatorIds | hwEnforcedUserAuthenticatorIds;
Set<Integer> userAuthenticators =
KeyStoreKeyConstraints.UserAuthenticator.allFromKeymaster(userAuthenticatorIds);
Set<Integer> teeBackedUserAuthenticators =
KeyStoreKeyConstraints.UserAuthenticator.allFromKeymaster(
hwEnforcedUserAuthenticatorIds);
return new KeyStoreKeySpec(entryAlias, return new KeyStoreKeySpec(entryAlias,
origin, origin,
@ -150,15 +151,13 @@ public class KeyStoreSecretKeyFactorySpi extends SecretKeyFactorySpi {
keyValidityForConsumptionEnd, keyValidityForConsumptionEnd,
purposes, purposes,
algorithm, algorithm,
padding, paddings,
digest, digests,
blockMode, blockModes,
KeymasterUtils.getInt(keyCharacteristics,
KeymasterDefs.KM_TAG_MIN_SECONDS_BETWEEN_OPS),
KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_MAX_USES_PER_BOOT),
userAuthenticators, userAuthenticators,
teeBackedUserAuthenticators, teeEnforcedUserAuthenticators,
KeymasterUtils.getInt(keyCharacteristics, KeymasterDefs.KM_TAG_AUTH_TIMEOUT)); ((userAuthenticationValidityDurationSeconds != null)
? userAuthenticationValidityDurationSeconds : -1));
} }
@Override @Override