No runtime exceptions during normal use of AndroidKeyStore crypto.

This changes the implementation of AndroidKeyStore-backed Cipher and
Mac to avoid throwing runtime exceptions during normal use. Runtime
exceptions will now be thrown only due to truly exceptional and
unrecoverable errors (e.g., keystore unreachable, or crypto primitive
not initialized).

This also changes the implementation of Cipher to cache any errors
encountered in Cipher.update until Cipher.doFinal which then throws
them as checked exceptions.

Bug: 20525947
Change-Id: I3c4ad57fe70abfbb817a79402f722a0208660727
This commit is contained in:
Alex Klyubin
2015-04-21 15:17:24 -07:00
parent 71223ebe1b
commit ad9ba10ecd
10 changed files with 102 additions and 95 deletions

View File

@@ -147,7 +147,7 @@ public abstract class KeyStoreHmacSpi extends MacSpi implements KeyStoreCryptoOp
resetWhilePreservingInitState();
}
private void ensureKeystoreOperationInitialized() {
private void ensureKeystoreOperationInitialized() throws InvalidKeyException {
if (mChunkedStreamer != null) {
return;
}
@@ -169,10 +169,10 @@ public abstract class KeyStoreHmacSpi extends MacSpi implements KeyStoreCryptoOp
if (opResult == null) {
throw new KeyStoreConnectException();
} else if (opResult.resultCode != KeyStore.NO_ERROR) {
throw KeyStore.getCryptoOperationException(opResult.resultCode);
throw KeyStore.getInvalidKeyException(opResult.resultCode);
}
if (opResult.token == null) {
throw new CryptoOperationException("Keystore returned null operation token");
throw new IllegalStateException("Keystore returned null operation token");
}
mOperationToken = opResult.token;
mOperationHandle = opResult.operationHandle;
@@ -188,28 +188,36 @@ public abstract class KeyStoreHmacSpi extends MacSpi implements KeyStoreCryptoOp
@Override
protected void engineUpdate(byte[] input, int offset, int len) {
ensureKeystoreOperationInitialized();
try {
ensureKeystoreOperationInitialized();
} catch (InvalidKeyException e) {
throw new IllegalStateException("Failed to reinitialize MAC", e);
}
byte[] output;
try {
output = mChunkedStreamer.update(input, offset, len);
} catch (KeyStoreException e) {
throw KeyStore.getCryptoOperationException(e);
throw new IllegalStateException("Keystore operation failed", e);
}
if ((output != null) && (output.length != 0)) {
throw new CryptoOperationException("Update operation unexpectedly produced output");
throw new IllegalStateException("Update operation unexpectedly produced output");
}
}
@Override
protected byte[] engineDoFinal() {
ensureKeystoreOperationInitialized();
try {
ensureKeystoreOperationInitialized();
} catch (InvalidKeyException e) {
throw new IllegalStateException("Failed to reinitialize MAC", e);
}
byte[] result;
try {
result = mChunkedStreamer.doFinal(null, 0, 0);
} catch (KeyStoreException e) {
throw KeyStore.getCryptoOperationException(e);
throw new IllegalStateException("Keystore operation failed", e);
}
resetWhilePreservingInitState();