• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.security.keystore;
18 
19 import android.annotation.FlaggedApi;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 
23 import java.security.PrivateKey;
24 import java.security.spec.KeySpec;
25 import java.util.Date;
26 
27 import javax.crypto.SecretKey;
28 
29 /**
30  * Information about a key from the <a href="{@docRoot}training/articles/keystore.html">Android
31  * Keystore system</a>. This class describes whether the key material is available in
32  * plaintext outside of secure hardware, whether user authentication is required for using the key
33  * and whether this requirement is enforced by secure hardware, the key's origin, what uses the key
34  * is authorized for (e.g., only in {@code GCM} mode, or signing only), whether the key should be
35  * encrypted at rest, the key's and validity start and end dates.
36  *
37  * <p>Instances of this class are immutable.
38  *
39  * <p><h3>Example: Symmetric Key</h3>
40  * The following example illustrates how to obtain a {@code KeyInfo} describing the provided Android
41  * Keystore {@link SecretKey}.
42  * <pre>{@code
43  * SecretKey key = ...; // Android Keystore key
44  *
45  * SecretKeyFactory factory = SecretKeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
46  * KeyInfo keyInfo;
47  * try {
48  *     keyInfo = (KeyInfo) factory.getKeySpec(key, KeyInfo.class);
49  * } catch (InvalidKeySpecException e) {
50  *     // Not an Android KeyStore key.
51  * }}</pre>
52  *
53  * <p><h3>Example: Private Key</h3>
54  * The following example illustrates how to obtain a {@code KeyInfo} describing the provided
55  * Android KeyStore {@link PrivateKey}.
56  * <pre>{@code
57  * PrivateKey key = ...; // Android KeyStore key
58  *
59  * KeyFactory factory = KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore");
60  * KeyInfo keyInfo;
61  * try {
62  *     keyInfo = factory.getKeySpec(key, KeyInfo.class);
63  * } catch (InvalidKeySpecException e) {
64  *     // Not an Android KeyStore key.
65  * }}</pre>
66  */
67 public class KeyInfo implements KeySpec {
68     private final String mKeystoreAlias;
69     private final int mKeySize;
70     private final boolean mInsideSecureHardware;
71     private final @KeyProperties.OriginEnum int mOrigin;
72     private final Date mKeyValidityStart;
73     private final Date mKeyValidityForOriginationEnd;
74     private final Date mKeyValidityForConsumptionEnd;
75     private final @KeyProperties.PurposeEnum int mPurposes;
76     private final @KeyProperties.EncryptionPaddingEnum String[] mEncryptionPaddings;
77     private final @KeyProperties.SignaturePaddingEnum String[] mSignaturePaddings;
78     private final @KeyProperties.DigestEnum String[] mDigests;
79     private final @KeyProperties.BlockModeEnum String[] mBlockModes;
80     private final boolean mUserAuthenticationRequired;
81     private final int mUserAuthenticationValidityDurationSeconds;
82     private final @KeyProperties.AuthEnum int mUserAuthenticationType;
83     private final boolean mUserAuthenticationRequirementEnforcedBySecureHardware;
84     private final boolean mUserAuthenticationValidWhileOnBody;
85     private final boolean mUnlockedDeviceRequired;
86     private final boolean mTrustedUserPresenceRequired;
87     private final boolean mInvalidatedByBiometricEnrollment;
88     private final boolean mUserConfirmationRequired;
89     private final @KeyProperties.SecurityLevelEnum int mSecurityLevel;
90     private final int mRemainingUsageCount;
91 
92     /**
93      * @hide
94      */
KeyInfo(String keystoreKeyAlias, boolean insideSecureHardware, @KeyProperties.OriginEnum int origin, int keySize, Date keyValidityStart, Date keyValidityForOriginationEnd, Date keyValidityForConsumptionEnd, @KeyProperties.PurposeEnum int purposes, @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings, @KeyProperties.SignaturePaddingEnum String[] signaturePaddings, @KeyProperties.DigestEnum String[] digests, @KeyProperties.BlockModeEnum String[] blockModes, boolean userAuthenticationRequired, int userAuthenticationValidityDurationSeconds, @KeyProperties.AuthEnum int userAuthenticationType, boolean userAuthenticationRequirementEnforcedBySecureHardware, boolean userAuthenticationValidWhileOnBody, boolean unlockedDeviceRequired, boolean trustedUserPresenceRequired, boolean invalidatedByBiometricEnrollment, boolean userConfirmationRequired, @KeyProperties.SecurityLevelEnum int securityLevel, int remainingUsageCount)95     public KeyInfo(String keystoreKeyAlias,
96             boolean insideSecureHardware,
97             @KeyProperties.OriginEnum int origin,
98             int keySize,
99             Date keyValidityStart,
100             Date keyValidityForOriginationEnd,
101             Date keyValidityForConsumptionEnd,
102             @KeyProperties.PurposeEnum int purposes,
103             @KeyProperties.EncryptionPaddingEnum String[] encryptionPaddings,
104             @KeyProperties.SignaturePaddingEnum String[] signaturePaddings,
105             @KeyProperties.DigestEnum String[] digests,
106             @KeyProperties.BlockModeEnum String[] blockModes,
107             boolean userAuthenticationRequired,
108             int userAuthenticationValidityDurationSeconds,
109             @KeyProperties.AuthEnum int userAuthenticationType,
110             boolean userAuthenticationRequirementEnforcedBySecureHardware,
111             boolean userAuthenticationValidWhileOnBody,
112             boolean unlockedDeviceRequired,
113             boolean trustedUserPresenceRequired,
114             boolean invalidatedByBiometricEnrollment,
115             boolean userConfirmationRequired,
116             @KeyProperties.SecurityLevelEnum int securityLevel,
117             int remainingUsageCount) {
118         mKeystoreAlias = keystoreKeyAlias;
119         mInsideSecureHardware = insideSecureHardware;
120         mOrigin = origin;
121         mKeySize = keySize;
122         mKeyValidityStart = Utils.cloneIfNotNull(keyValidityStart);
123         mKeyValidityForOriginationEnd = Utils.cloneIfNotNull(keyValidityForOriginationEnd);
124         mKeyValidityForConsumptionEnd = Utils.cloneIfNotNull(keyValidityForConsumptionEnd);
125         mPurposes = purposes;
126         mEncryptionPaddings =
127                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(encryptionPaddings));
128         mSignaturePaddings =
129                 ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(signaturePaddings));
130         mDigests = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(digests));
131         mBlockModes = ArrayUtils.cloneIfNotEmpty(ArrayUtils.nullToEmpty(blockModes));
132         mUserAuthenticationRequired = userAuthenticationRequired;
133         mUserAuthenticationValidityDurationSeconds = userAuthenticationValidityDurationSeconds;
134         mUserAuthenticationType = userAuthenticationType;
135         mUserAuthenticationRequirementEnforcedBySecureHardware =
136                 userAuthenticationRequirementEnforcedBySecureHardware;
137         mUserAuthenticationValidWhileOnBody = userAuthenticationValidWhileOnBody;
138         mUnlockedDeviceRequired = unlockedDeviceRequired;
139         mTrustedUserPresenceRequired = trustedUserPresenceRequired;
140         mInvalidatedByBiometricEnrollment = invalidatedByBiometricEnrollment;
141         mUserConfirmationRequired = userConfirmationRequired;
142         mSecurityLevel = securityLevel;
143         mRemainingUsageCount = remainingUsageCount;
144     }
145 
146     /**
147      * Gets the entry alias under which the key is stored in the {@code AndroidKeyStore}.
148      */
getKeystoreAlias()149     public String getKeystoreAlias() {
150         return mKeystoreAlias;
151     }
152 
153     /**
154      * Returns {@code true} if the key resides inside secure hardware (e.g., Trusted Execution
155      * Environment (TEE) or Secure Element (SE)). Key material of such keys is available in
156      * plaintext only inside the secure hardware and is not exposed outside of it.
157      *
158      * @deprecated This method is superseded by @see getSecurityLevel.
159      */
160     @Deprecated
isInsideSecureHardware()161     public boolean isInsideSecureHardware() {
162         return mInsideSecureHardware;
163     }
164 
165     /**
166      * Gets the origin of the key. See {@link KeyProperties}.{@code ORIGIN} constants.
167      */
getOrigin()168     public @KeyProperties.OriginEnum int getOrigin() {
169         return mOrigin;
170     }
171 
172     /**
173      * Gets the size of the key in bits.
174      */
getKeySize()175     public int getKeySize() {
176         return mKeySize;
177     }
178 
179     /**
180      * Gets the time instant before which the key is not yet valid.
181      *
182      * @return instant or {@code null} if not restricted.
183      */
184     @Nullable
getKeyValidityStart()185     public Date getKeyValidityStart() {
186         return Utils.cloneIfNotNull(mKeyValidityStart);
187     }
188 
189     /**
190      * Gets the time instant after which the key is no long valid for decryption and verification.
191      *
192      * @return instant or {@code null} if not restricted.
193      */
194     @Nullable
getKeyValidityForConsumptionEnd()195     public Date getKeyValidityForConsumptionEnd() {
196         return Utils.cloneIfNotNull(mKeyValidityForConsumptionEnd);
197     }
198 
199     /**
200      * Gets the time instant after which the key is no long valid for encryption and signing.
201      *
202      * @return instant or {@code null} if not restricted.
203      */
204     @Nullable
getKeyValidityForOriginationEnd()205     public Date getKeyValidityForOriginationEnd() {
206         return Utils.cloneIfNotNull(mKeyValidityForOriginationEnd);
207     }
208 
209     /**
210      * Gets the set of purposes (e.g., encrypt, decrypt, sign) for which the key can be used.
211      * Attempts to use the key for any other purpose will be rejected.
212      *
213      * <p>See {@link KeyProperties}.{@code PURPOSE} flags.
214      */
getPurposes()215     public @KeyProperties.PurposeEnum int getPurposes() {
216         return mPurposes;
217     }
218 
219     /**
220      * Gets the set of block modes (e.g., {@code GCM}, {@code CBC}) with which the key can be used
221      * when encrypting/decrypting. Attempts to use the key with any other block modes will be
222      * rejected.
223      *
224      * <p>See {@link KeyProperties}.{@code BLOCK_MODE} constants.
225      */
226     @NonNull
getBlockModes()227     public @KeyProperties.BlockModeEnum String[] getBlockModes() {
228         return ArrayUtils.cloneIfNotEmpty(mBlockModes);
229     }
230 
231     /**
232      * Gets the set of padding schemes (e.g., {@code PKCS7Padding}, {@code PKCS1Padding},
233      * {@code NoPadding}) with which the key can be used when encrypting/decrypting. Attempts to use
234      * the key with any other padding scheme will be rejected.
235      *
236      * <p>See {@link KeyProperties}.{@code ENCRYPTION_PADDING} constants.
237      */
238     @NonNull
getEncryptionPaddings()239     public @KeyProperties.EncryptionPaddingEnum String[] getEncryptionPaddings() {
240         return ArrayUtils.cloneIfNotEmpty(mEncryptionPaddings);
241     }
242 
243     /**
244      * Gets the set of padding schemes (e.g., {@code PSS}, {@code PKCS#1}) with which the key
245      * can be used when signing/verifying. Attempts to use the key with any other padding scheme
246      * will be rejected.
247      *
248      * <p>See {@link KeyProperties}.{@code SIGNATURE_PADDING} constants.
249      */
250     @NonNull
getSignaturePaddings()251     public @KeyProperties.SignaturePaddingEnum String[] getSignaturePaddings() {
252         return ArrayUtils.cloneIfNotEmpty(mSignaturePaddings);
253     }
254 
255     /**
256      * Gets the set of digest algorithms (e.g., {@code SHA-256}, {@code SHA-384}) with which the key
257      * can be used.
258      *
259      * <p>See {@link KeyProperties}.{@code DIGEST} constants.
260      */
261     @NonNull
getDigests()262     public @KeyProperties.DigestEnum String[] getDigests() {
263         return ArrayUtils.cloneIfNotEmpty(mDigests);
264     }
265 
266     /**
267      * Returns {@code true} if the key is authorized to be used only if the user has been
268      * authenticated.
269      *
270      * <p>This authorization applies only to secret key and private key operations. Public key
271      * operations are not restricted.
272      *
273      * @see #getUserAuthenticationValidityDurationSeconds()
274      * @see KeyGenParameterSpec.Builder#setUserAuthenticationRequired(boolean)
275      * @see KeyProtection.Builder#setUserAuthenticationRequired(boolean)
276      */
isUserAuthenticationRequired()277     public boolean isUserAuthenticationRequired() {
278         return mUserAuthenticationRequired;
279     }
280 
281     /**
282      * Returns {@code true} if the key is authorized to be used only while the device is unlocked.
283      *
284      * <p>This authorization applies only to secret key and private key operations. Public key
285      * operations are not restricted.
286      *
287      * @see KeyGenParameterSpec.Builder#setUnlockedDeviceRequired(boolean)
288      * @see KeyProtection.Builder#setUnlockedDeviceRequired(boolean)
289      */
290     @FlaggedApi(android.security.Flags.FLAG_KEYINFO_UNLOCKED_DEVICE_REQUIRED)
isUnlockedDeviceRequired()291     public boolean isUnlockedDeviceRequired() {
292         return mUnlockedDeviceRequired;
293     }
294 
295     /**
296      * Returns {@code true} if the key is authorized to be used only for messages confirmed by the
297      * user.
298      *
299      * Confirmation is separate from user authentication (see
300      * {@link #isUserAuthenticationRequired()}). Keys can be created that require confirmation but
301      * not user authentication, or user authentication but not confirmation, or both. Confirmation
302      * verifies that some user with physical possession of the device has approved a displayed
303      * message. User authentication verifies that the correct user is present and has
304      * authenticated.
305      *
306      * <p>This authorization applies only to secret key and private key operations. Public key
307      * operations are not restricted.
308      *
309      * @see KeyGenParameterSpec.Builder#setUserConfirmationRequired(boolean)
310      * @see KeyProtection.Builder#setUserConfirmationRequired(boolean)
311      */
isUserConfirmationRequired()312     public boolean isUserConfirmationRequired() {
313         return mUserConfirmationRequired;
314     }
315 
316     /**
317      * Gets the duration of time (seconds) for which this key is authorized to be used after the
318      * user is successfully authenticated. This has effect only if user authentication is required
319      * (see {@link #isUserAuthenticationRequired()}).
320      *
321      * <p>This authorization applies only to secret key and private key operations. Public key
322      * operations are not restricted.
323      *
324      * @return duration in seconds or {@code -1} if authentication is required for every use of the
325      *         key.
326      *
327      * @see #isUserAuthenticationRequired()
328      */
getUserAuthenticationValidityDurationSeconds()329     public int getUserAuthenticationValidityDurationSeconds() {
330         return mUserAuthenticationValidityDurationSeconds;
331     }
332 
333     /**
334      * Gets the acceptable user authentication types for which this key can be authorized to be
335      * used. This has effect only if user authentication is required (see
336      * {@link #isUserAuthenticationRequired()}).
337      *
338      * <p>This authorization applies only to secret key and private key operations. Public key
339      * operations are not restricted.
340      *
341      * @return integer representing the accepted forms of user authentication for this key
342      *
343      * @see #isUserAuthenticationRequired()
344      */
getUserAuthenticationType()345     public @KeyProperties.AuthEnum int getUserAuthenticationType() {
346         return mUserAuthenticationType;
347     }
348 
349     /**
350      * Returns {@code true} if the requirement that this key can only be used if the user has been
351      * authenticated is enforced by secure hardware (e.g., Trusted Execution Environment (TEE) or
352      * Secure Element (SE)).
353      *
354      * @see #isUserAuthenticationRequired()
355      */
isUserAuthenticationRequirementEnforcedBySecureHardware()356     public boolean isUserAuthenticationRequirementEnforcedBySecureHardware() {
357         return mUserAuthenticationRequirementEnforcedBySecureHardware;
358     }
359 
360     /**
361      * Returns {@code true} if this key will become unusable when the device is removed from the
362      * user's body.  This is possible only for keys with a specified validity duration, and only on
363      * devices with an on-body sensor.  Always returns {@code false} on devices that lack an on-body
364      * sensor.
365      */
isUserAuthenticationValidWhileOnBody()366     public boolean isUserAuthenticationValidWhileOnBody() {
367         return mUserAuthenticationValidWhileOnBody;
368     }
369 
370     /**
371      * Returns {@code true} if the key will be invalidated by enrollment of a new fingerprint or
372      * removal of all fingerprints.
373      */
isInvalidatedByBiometricEnrollment()374     public boolean isInvalidatedByBiometricEnrollment() {
375         return mInvalidatedByBiometricEnrollment;
376     }
377 
378     /**
379      * Returns {@code true} if the key can only be only be used if a test for user presence has
380      * succeeded since Signature.initSign() has been called.
381      */
isTrustedUserPresenceRequired()382     public boolean isTrustedUserPresenceRequired() {
383         return mTrustedUserPresenceRequired;
384     }
385 
386     /**
387      * Returns the security level that the key is protected by.
388      * {@code KeyProperties.SecurityLevelEnum.TRUSTED_ENVIRONMENT} and
389      * {@code KeyProperties.SecurityLevelEnum.STRONGBOX} indicate that the key material resides
390      * in secure hardware. Key material of such keys is available in
391      * plaintext only inside the secure hardware and is not exposed outside of it.
392      *
393      * <p>See {@link KeyProperties}.{@code SecurityLevelEnum} constants.
394      */
getSecurityLevel()395     public @KeyProperties.SecurityLevelEnum int getSecurityLevel() {
396         return mSecurityLevel;
397     }
398 
399     /**
400      * Returns the remaining number of times the key is allowed to be used or
401      * {@link KeyProperties#UNRESTRICTED_USAGE_COUNT} if there's no restriction on the number of
402      * times the key can be used. Note that this gives a best effort count and need not be
403      * accurate (as there might be usages happening in parallel and the count maintained here need
404      * not be in sync with the usage).
405      */
getRemainingUsageCount()406     public int getRemainingUsageCount() {
407         return mRemainingUsageCount;
408     }
409 }
410