Reputation: 447
I have the following code that tries to initialize KeyManagerFactory using SHA-256 hash as password.
public static KeyManager[] getKeystoreManagers()
throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException {
KeyStore keystore = getKeyStore();
if (keystore == null) {
return null;
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keystore, getMachinePassword(SHA_256).toCharArray());
return kmf.getKeyManagers();
}
getKeyStore() returns my application keystore. getMachinePassword() returns a password using SHA-256, 64 digits password length.
The problem is that I get the exception when init() is called:
java.security.UnrecoverableKeyException: Cannot recover key
If I am passing smaller password length lets say, 50 digits the init succeeded.
What seems to be the problem here?
Upvotes: 1
Views: 7161
Reputation: 447
I've solved my problem. The keystore was created using setEntry with specific alias.
Therefore, in my conversion function I had to get the entry using the old password and set the same entry with the same alias again with the new password. Now, with this updated keystore the KeyManagerFactory.init()
runs successfully. See the following code below:
static void convertPasswordAlgorithm(String keystorePath, String fromAlgorithm, String toAlgorithm) throws Exceptionc {
FileInputStream fileInStream = null;
String keystoreFullPath = keystorePath + ISiteConstants.c_FILE_SEPERATOR + KEYSTORE_FILE_NAME;
KeyStore keyStore;
try {
String alias = getCertificateAlias();
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
fileInStream = new FileInputStream(keystoreFullPath);
// Try to load the keystore with fromAlgorithm password hash.
char[] machineOldAlgPassword = getMachinePassword(fromAlgorithm).toCharArray();
keyStore.load(fileInStream, machineOldAlgPassword);
// Save the entry to update
KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(machineOldAlgPassword));
HandleFiles.close(fileInStream);
// If succeeded, recalculate password using toAlgorithm hash and save.
String machineNewAlgPassword = getMachinePassword(toAlgorithm);
keyStore.setEntry(alias, entry, new KeyStore.PasswordProtection(machineNewAlgPassword.toCharArray()));
FileOutputStream fileOutputStream = new FileOutputStream(keystoreFullPath);
keyStore.store(fileOutputStream, machineNewAlgPassword.toCharArray());
HandleFiles.close(fileOutputStream);
} finally {
HandleFiles.close(fileInStream);
}
}
Upvotes: 1