1 /*
2  * Copyright (C) 2019 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 com.android.cts.authboundkeyapp;
18 
19 import static junit.framework.Assert.assertFalse;
20 
21 import static org.junit.Assert.assertNotNull;
22 import static org.junit.Assert.assertNull;
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.fail;
25 
26 import android.content.BroadcastReceiver;
27 import android.content.Context;
28 import android.security.keystore.KeyGenParameterSpec;
29 import android.security.keystore.KeyPermanentlyInvalidatedException;
30 import android.security.keystore.KeyProperties;
31 import android.test.AndroidTestCase;
32 import android.test.MoreAsserts;
33 import android.util.Log;
34 
35 import java.security.KeyStore;
36 import java.security.UnrecoverableKeyException;
37 
38 import javax.crypto.Cipher;
39 import javax.crypto.KeyGenerator;
40 import javax.crypto.SecretKey;
41 
42 public class AuthBoundKeyAppTest extends AndroidTestCase {
43     private static final String KEY_NAME = "nice_key";
44     private static final String KEYSTORE = "AndroidKeyStore";
testGenerateAuthBoundKey()45     public void testGenerateAuthBoundKey() throws Exception {
46         KeyStore keyStore = KeyStore.getInstance(KEYSTORE);
47         keyStore.load(null);
48         KeyGenerator keyGenerator = KeyGenerator.getInstance(
49                 KeyProperties.KEY_ALGORITHM_AES, KEYSTORE);
50         keyGenerator.init(new KeyGenParameterSpec.Builder(
51             KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
52             .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
53             .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
54             .setUserAuthenticationRequired(true)
55             .setUserAuthenticationValidityDurationSeconds(15)
56             .build());
57         keyGenerator.generateKey();
58     }
59 
testUseKey()60     public void testUseKey() throws Exception {
61         KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
62         keyStore.load(null);
63         try {
64             SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);
65         } catch (UnrecoverableKeyException e) {
66             // This is correct behavior
67             return;
68         }
69         fail("Expected an UnrecoverableKeyException");
70     }
71 
72 }
73