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