1/* 2 * Copyright (C) 2017 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 17package com.android.server.locksettings.recoverablekeystore; 18 19import java.io.IOException; 20import java.security.cert.CertificateException; 21import java.security.Key; 22import java.security.KeyStore; 23import java.security.KeyStoreException; 24import java.security.NoSuchAlgorithmException; 25import java.security.NoSuchAlgorithmException; 26import java.security.UnrecoverableKeyException; 27 28/** 29 * Implementation of {@link KeyStoreProxy} that delegates all method calls to the {@link KeyStore}. 30 */ 31public class KeyStoreProxyImpl implements KeyStoreProxy { 32 33 private static final String ANDROID_KEY_STORE_PROVIDER = "AndroidKeyStore"; 34 private final KeyStore mKeyStore; 35 36 /** 37 * A new instance, delegating to {@code keyStore}. 38 */ 39 public KeyStoreProxyImpl(KeyStore keyStore) { 40 mKeyStore = keyStore; 41 } 42 43 @Override 44 public boolean containsAlias(String alias) throws KeyStoreException { 45 return mKeyStore.containsAlias(alias); 46 } 47 48 @Override 49 public Key getKey(String alias, char[] password) 50 throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { 51 return mKeyStore.getKey(alias, password); 52 } 53 54 @Override 55 public void setEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam) 56 throws KeyStoreException { 57 mKeyStore.setEntry(alias, entry, protParam); 58 } 59 60 @Override 61 public void deleteEntry(String alias) throws KeyStoreException { 62 mKeyStore.deleteEntry(alias); 63 } 64 65 /** 66 * Returns AndroidKeyStore-provided {@link KeyStore}, having already invoked 67 * {@link KeyStore#load(KeyStore.LoadStoreParameter)}. 68 * 69 * @throws KeyStoreException if there was a problem getting or initializing the key store. 70 */ 71 public static KeyStore getAndLoadAndroidKeyStore() throws KeyStoreException { 72 KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE_PROVIDER); 73 try { 74 keyStore.load(/*param=*/ null); 75 } catch (CertificateException | IOException | NoSuchAlgorithmException e) { 76 // Should never happen. 77 throw new KeyStoreException("Unable to load keystore.", e); 78 } 79 return keyStore; 80 } 81} 82