use of java.security.UnrecoverableKeyException in project android_frameworks_base by DirtyUnicorns.
the class LockSettingsService method tieProfileLockToParent.
private void tieProfileLockToParent(int userId, String password) {
if (DEBUG)
Slog.v(TAG, "tieProfileLockToParent for user: " + userId);
byte[] randomLockSeed = password.getBytes(StandardCharsets.UTF_8);
byte[] encryptionResult;
byte[] iv;
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
keyGenerator.init(new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
try {
keyStore.setEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, new java.security.KeyStore.SecretKeyEntry(secretKey), new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
keyStore.setEntry(LockPatternUtils.PROFILE_KEY_NAME_DECRYPT + userId, new java.security.KeyStore.SecretKeyEntry(secretKey), new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_GCM).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).setUserAuthenticationRequired(true).setUserAuthenticationValidityDurationSeconds(30).build());
// Key imported, obtain a reference to it.
SecretKey keyStoreEncryptionKey = (SecretKey) keyStore.getKey(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId, null);
Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_GCM + "/" + KeyProperties.ENCRYPTION_PADDING_NONE);
cipher.init(Cipher.ENCRYPT_MODE, keyStoreEncryptionKey);
encryptionResult = cipher.doFinal(randomLockSeed);
iv = cipher.getIV();
} finally {
// The original key can now be discarded.
keyStore.deleteEntry(LockPatternUtils.PROFILE_KEY_NAME_ENCRYPT + userId);
}
} catch (CertificateException | UnrecoverableKeyException | IOException | BadPaddingException | IllegalBlockSizeException | KeyStoreException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to encrypt key", e);
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
if (iv.length != PROFILE_KEY_IV_SIZE) {
throw new RuntimeException("Invalid iv length: " + iv.length);
}
outputStream.write(iv);
outputStream.write(encryptionResult);
} catch (IOException e) {
throw new RuntimeException("Failed to concatenate byte arrays", e);
}
mStorage.writeChildProfileLock(userId, outputStream.toByteArray());
}
use of java.security.UnrecoverableKeyException in project android_frameworks_base by DirtyUnicorns.
the class LockSettingsService method setLockPasswordInternal.
private void setLockPasswordInternal(String password, String savedCredential, int userId) throws RemoteException {
byte[] currentHandle = getCurrentHandle(userId);
if (password == null) {
clearUserKeyProtection(userId);
getGateKeeperService().clearSecureUserId(userId);
mStorage.writePasswordHash(null, userId);
setKeystorePassword(null, userId);
fixateNewestUserKeyAuth(userId);
onUserLockChanged(userId);
notifyActivePasswordMetricsAvailable(null, userId);
return;
}
if (isManagedProfileWithUnifiedLock(userId)) {
// get credential from keystore when managed profile has unified lock
try {
savedCredential = getDecryptedPasswordForTiedProfile(userId);
} catch (FileNotFoundException e) {
Slog.i(TAG, "Child profile key not found");
} catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
Slog.e(TAG, "Failed to decrypt child profile key", e);
}
} else {
if (currentHandle == null) {
if (savedCredential != null) {
Slog.w(TAG, "Saved credential provided, but none stored");
}
savedCredential = null;
}
}
byte[] enrolledHandle = enrollCredential(currentHandle, savedCredential, password, userId);
if (enrolledHandle != null) {
CredentialHash willStore = new CredentialHash(enrolledHandle, CredentialHash.VERSION_GATEKEEPER);
setUserKeyProtection(userId, password, doVerifyPassword(password, willStore, true, 0, userId, null));
mStorage.writePasswordHash(enrolledHandle, userId);
fixateNewestUserKeyAuth(userId);
onUserLockChanged(userId);
} else {
throw new RemoteException("Failed to enroll password");
}
}
use of java.security.UnrecoverableKeyException in project android_frameworks_base by DirtyUnicorns.
the class LockSettingsService method setLockPatternInternal.
private void setLockPatternInternal(String pattern, String savedCredential, int userId) throws RemoteException {
byte[] currentHandle = getCurrentHandle(userId);
if (pattern == null) {
clearUserKeyProtection(userId);
getGateKeeperService().clearSecureUserId(userId);
mStorage.writePatternHash(null, userId);
setKeystorePassword(null, userId);
fixateNewestUserKeyAuth(userId);
onUserLockChanged(userId);
notifyActivePasswordMetricsAvailable(null, userId);
return;
}
if (isManagedProfileWithUnifiedLock(userId)) {
// get credential from keystore when managed profile has unified lock
try {
savedCredential = getDecryptedPasswordForTiedProfile(userId);
} catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
if (e instanceof FileNotFoundException) {
Slog.i(TAG, "Child profile key not found");
} else {
Slog.e(TAG, "Failed to decrypt child profile key", e);
}
}
} else {
if (currentHandle == null) {
if (savedCredential != null) {
Slog.w(TAG, "Saved credential provided, but none stored");
}
savedCredential = null;
}
}
byte[] enrolledHandle = enrollCredential(currentHandle, savedCredential, pattern, userId);
if (enrolledHandle != null) {
CredentialHash willStore = new CredentialHash(enrolledHandle, CredentialHash.VERSION_GATEKEEPER);
setUserKeyProtection(userId, pattern, doVerifyPattern(pattern, willStore, true, 0, userId, null));
mStorage.writePatternHash(enrolledHandle, userId);
fixateNewestUserKeyAuth(userId);
onUserLockChanged(userId);
} else {
throw new RemoteException("Failed to enroll pattern");
}
}
use of java.security.UnrecoverableKeyException in project otertool by wuntee.
the class JarSigner method getAliasInfo.
void getAliasInfo(String alias) throws JarSigningException {
Key key = null;
try {
java.security.cert.Certificate[] cs = null;
try {
cs = store.getCertificateChain(alias);
} catch (KeyStoreException kse) {
// this never happens, because keystore has been loaded
}
if (cs == null) {
MessageFormat form = new MessageFormat(rb.getString("Certificate chain not found for: alias. alias must reference a valid KeyStore key entry containing a private key and corresponding public key certificate chain."));
Object[] source = { alias, alias };
error(form.format(source));
}
certChain = new X509Certificate[cs.length];
for (int i = 0; i < cs.length; i++) {
if (!(cs[i] instanceof X509Certificate)) {
error(rb.getString("found non-X.509 certificate in signer's chain"));
}
certChain[i] = (X509Certificate) cs[i];
}
// order the cert chain if necessary (put user cert first,
// root-cert last in the chain)
X509Certificate userCert = (X509Certificate) store.getCertificate(alias);
// check validity of signer certificate
try {
userCert.checkValidity();
if (userCert.getNotAfter().getTime() < System.currentTimeMillis() + SIX_MONTHS) {
hasExpiringCert = true;
}
} catch (CertificateExpiredException cee) {
hasExpiredCert = true;
} catch (CertificateNotYetValidException cnyve) {
notYetValidCert = true;
}
checkCertUsage(userCert, null);
if (!userCert.equals(certChain[0])) {
// need to order ...
X509Certificate[] certChainTmp = new X509Certificate[certChain.length];
certChainTmp[0] = userCert;
Principal issuer = userCert.getIssuerDN();
for (int i = 1; i < certChain.length; i++) {
int j;
// given issuer
for (j = 0; j < certChainTmp.length; j++) {
if (certChainTmp[j] == null)
continue;
Principal subject = certChainTmp[j].getSubjectDN();
if (issuer.equals(subject)) {
certChain[i] = certChainTmp[j];
issuer = certChainTmp[j].getIssuerDN();
certChainTmp[j] = null;
break;
}
}
if (j == certChainTmp.length) {
error(rb.getString("incomplete certificate chain"));
}
}
// ordered
certChain = certChainTmp;
}
try {
if (!token && keypass == null)
key = store.getKey(alias, storepass);
else
key = store.getKey(alias, keypass);
} catch (UnrecoverableKeyException e) {
if (token) {
throw e;
}
}
} catch (NoSuchAlgorithmException e) {
error(e.getMessage());
} catch (UnrecoverableKeyException e) {
error(rb.getString("unable to recover key from keystore"));
} catch (KeyStoreException kse) {
// this never happens, because keystore has been loaded
}
if (!(key instanceof PrivateKey)) {
MessageFormat form = new MessageFormat(rb.getString("key associated with alias not a private key"));
Object[] source = { alias };
error(form.format(source));
} else {
privateKey = (PrivateKey) key;
}
}
use of java.security.UnrecoverableKeyException in project android_frameworks_base by AOSPA.
the class AndroidKeyStoreProvider method loadAndroidKeyStorePublicKeyFromKeystore.
@NonNull
public static AndroidKeyStorePublicKey loadAndroidKeyStorePublicKeyFromKeystore(@NonNull KeyStore keyStore, @NonNull String privateKeyAlias, int uid) throws UnrecoverableKeyException {
KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
int errorCode = keyStore.getKeyCharacteristics(privateKeyAlias, null, null, uid, keyCharacteristics);
if (errorCode != KeyStore.NO_ERROR) {
throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain information about private key").initCause(KeyStore.getKeyStoreException(errorCode));
}
ExportResult exportResult = keyStore.exportKey(privateKeyAlias, KeymasterDefs.KM_KEY_FORMAT_X509, null, null, uid);
if (exportResult.resultCode != KeyStore.NO_ERROR) {
throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to obtain X.509 form of public key").initCause(KeyStore.getKeyStoreException(exportResult.resultCode));
}
final byte[] x509EncodedPublicKey = exportResult.exportData;
Integer keymasterAlgorithm = keyCharacteristics.getEnum(KeymasterDefs.KM_TAG_ALGORITHM);
if (keymasterAlgorithm == null) {
throw new UnrecoverableKeyException("Key algorithm unknown");
}
String jcaKeyAlgorithm;
try {
jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
} catch (IllegalArgumentException e) {
throw (UnrecoverableKeyException) new UnrecoverableKeyException("Failed to load private key").initCause(e);
}
return AndroidKeyStoreProvider.getAndroidKeyStorePublicKey(privateKeyAlias, uid, jcaKeyAlgorithm, x509EncodedPublicKey);
}
Aggregations