use of java.security.UnrecoverableKeyException in project android_frameworks_base by ResurrectionRemix.
the class LockSettingsService method verifyTiedProfileChallenge.
@Override
public VerifyCredentialResponse verifyTiedProfileChallenge(String password, boolean isPattern, long challenge, int userId) throws RemoteException {
checkPasswordReadPermission(userId);
if (!isManagedProfileWithUnifiedLock(userId)) {
throw new RemoteException("User id must be managed profile with unified lock");
}
final int parentProfileId = mUserManager.getProfileParent(userId).id;
// Unlock parent by using parent's challenge
final VerifyCredentialResponse parentResponse = isPattern ? doVerifyPattern(password, true, challenge, parentProfileId, null) : doVerifyPassword(password, true, challenge, parentProfileId, null);
if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
// Failed, just return parent's response
return parentResponse;
}
try {
// Unlock work profile, and work profile with unified lock must use password only
return doVerifyPassword(getDecryptedPasswordForTiedProfile(userId), true, challenge, userId, null);
} catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
Slog.e(TAG, "Failed to decrypt child profile key", e);
throw new RemoteException("Unable to get tied profile token");
}
}
use of java.security.UnrecoverableKeyException in project android_frameworks_base by ResurrectionRemix.
the class LockSettingsService method resetKeyStore.
@Override
public void resetKeyStore(int userId) throws RemoteException {
checkWritePermission(userId);
if (DEBUG)
Slog.v(TAG, "Reset keystore for user: " + userId);
int managedUserId = -1;
String managedUserDecryptedPassword = null;
final List<UserInfo> profiles = mUserManager.getProfiles(userId);
for (UserInfo pi : profiles) {
// Unlock managed profile with unified lock
if (pi.isManagedProfile() && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id) && mStorage.hasChildProfileLock(pi.id)) {
try {
if (managedUserId == -1) {
managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
managedUserId = pi.id;
} else {
// Should not happen
Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId + ", uid2:" + pi.id);
}
} catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
Slog.e(TAG, "Failed to decrypt child profile key", e);
}
}
}
try {
// Clear all the users credentials could have been installed in for this user.
for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
for (int uid : SYSTEM_CREDENTIAL_UIDS) {
mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
}
}
} finally {
if (managedUserId != -1 && managedUserDecryptedPassword != null) {
if (DEBUG)
Slog.v(TAG, "Restore tied profile lock");
tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
}
}
}
use of java.security.UnrecoverableKeyException in project android_frameworks_base by ResurrectionRemix.
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 jdk8u_jdk by JetBrains.
the class PKCS12KeyStore method engineGetKey.
/**
* Returns the key associated with the given alias, using the given
* password to recover it.
*
* @param alias the alias name
* @param password the password for recovering the key
*
* @return the requested key, or null if the given alias does not exist
* or does not identify a <i>key entry</i>.
*
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* key cannot be found
* @exception UnrecoverableKeyException if the key cannot be recovered
* (e.g., the given password is wrong).
*/
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException {
Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
Key key = null;
if (entry == null || (!(entry instanceof KeyEntry))) {
return null;
}
// get the encoded private key or secret key
byte[] encrBytes = null;
if (entry instanceof PrivateKeyEntry) {
encrBytes = ((PrivateKeyEntry) entry).protectedPrivKey;
} else if (entry instanceof SecretKeyEntry) {
encrBytes = ((SecretKeyEntry) entry).protectedSecretKey;
} else {
throw new UnrecoverableKeyException("Error locating key");
}
byte[] encryptedKey;
AlgorithmParameters algParams;
ObjectIdentifier algOid;
try {
// get the encrypted private key
EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(encrBytes);
encryptedKey = encrInfo.getEncryptedData();
// parse Algorithm parameters
DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
DerInputStream in = val.toDerInputStream();
algOid = in.getOID();
algParams = parseAlgParameters(algOid, in);
} catch (IOException ioe) {
UnrecoverableKeyException uke = new UnrecoverableKeyException("Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
uke.initCause(ioe);
throw uke;
}
try {
byte[] keyInfo;
while (true) {
try {
// Use JCE
SecretKey skey = getPBEKey(password);
Cipher cipher = Cipher.getInstance(mapPBEParamsToAlgorithm(algOid, algParams));
cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
keyInfo = cipher.doFinal(encryptedKey);
break;
} catch (Exception e) {
if (password.length == 0) {
// Retry using an empty password
// without a NULL terminator.
password = new char[1];
continue;
}
throw e;
}
}
/*
* Parse the key algorithm and then use a JCA key factory
* to re-create the key.
*/
DerValue val = new DerValue(keyInfo);
DerInputStream in = val.toDerInputStream();
int i = in.getInteger();
DerValue[] value = in.getSequence(2);
AlgorithmId algId = new AlgorithmId(value[0].getOID());
String keyAlgo = algId.getName();
// decode private key
if (entry instanceof PrivateKeyEntry) {
KeyFactory kfac = KeyFactory.getInstance(keyAlgo);
PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(keyInfo);
key = kfac.generatePrivate(kspec);
if (debug != null) {
debug.println("Retrieved a protected private key (" + key.getClass().getName() + ") at alias '" + alias + "'");
}
// decode secret key
} else {
byte[] keyBytes = in.getOctetString();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, keyAlgo);
// Special handling required for PBE: needs a PBEKeySpec
if (keyAlgo.startsWith("PBE")) {
SecretKeyFactory sKeyFactory = SecretKeyFactory.getInstance(keyAlgo);
KeySpec pbeKeySpec = sKeyFactory.getKeySpec(secretKeySpec, PBEKeySpec.class);
key = sKeyFactory.generateSecret(pbeKeySpec);
} else {
key = secretKeySpec;
}
if (debug != null) {
debug.println("Retrieved a protected secret key (" + key.getClass().getName() + ") at alias '" + alias + "'");
}
}
} catch (Exception e) {
UnrecoverableKeyException uke = new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
uke.initCause(e);
throw uke;
}
return key;
}
use of java.security.UnrecoverableKeyException in project jdk8u_jdk by JetBrains.
the class Pair method recoverKey.
/**
* Recovers (private) key associated with given alias.
*
* @return an array of objects, where the 1st element in the array is the
* recovered private key, and the 2nd element is the password used to
* recover it.
*/
private Pair<Key, char[]> recoverKey(String alias, char[] storePass, char[] keyPass) throws Exception {
Key key = null;
if (keyStore.containsAlias(alias) == false) {
MessageFormat form = new MessageFormat(rb.getString("Alias.alias.does.not.exist"));
Object[] source = { alias };
throw new Exception(form.format(source));
}
if (!keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class) && !keyStore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
MessageFormat form = new MessageFormat(rb.getString("Alias.alias.has.no.key"));
Object[] source = { alias };
throw new Exception(form.format(source));
}
if (keyPass == null) {
// Try to recover the key using the keystore password
try {
key = keyStore.getKey(alias, storePass);
keyPass = storePass;
passwords.add(keyPass);
} catch (UnrecoverableKeyException e) {
// Did not work out, so prompt user for key password
if (!token) {
keyPass = getKeyPasswd(alias, null, null);
key = keyStore.getKey(alias, keyPass);
} else {
throw e;
}
}
} else {
key = keyStore.getKey(alias, keyPass);
}
return Pair.of(key, keyPass);
}
Aggregations