我正在使用KeyStore安全地保存电子邮件和密码,并且在较新的设备上可以正常使用。 在某些较旧的版本(例如Lenovo A1010(Android 5.1-22))上,尝试获取证书时得到null。
private static void createKeysPreM(@NonNull Context context, @NonNull final String alias) throws NoSuchProviderException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException {
final Calendar start = new GregorianCalendar();
final Calendar end = new GregorianCalendar();
end.add(Calendar.YEAR, KEY_VALIDITY_YEARS);
final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
// You'll use the alias later to retrieve the key. It's a key for the key!
.setAlias(alias)
.setSubject(new X500Principal("CN=" + alias))
.setSerialNumber(BigInteger.valueOf(Math.abs(alias.hashCode())))
// Date range of validity for the generated pair.
.setStartDate(start.getTime()).setEndDate(end.getTime())
.build();
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(
SecurityConstants.TYPE_RSA,
SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
kpGenerator.initialize(spec);
}
private Certificate getCertificate() {
try {
final KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
ks.load(null);
return ks.getCertificate(KEY_STORE_ALIAS); //NULL ???
} catch (Exception e) {
Timber.d(e);
return null;
}
}
public interface SecurityConstants {
String KEYSTORE_PROVIDER_ANDROID_KEYSTORE = "AndroidKeyStore";
String TYPE_RSA = "RSA";
String PADDING_TYPE = "PKCS1Padding";
String BLOCKING_MODE = "NONE";
}
知道为什么会发生这种情况吗?我没有任何异常,在getCertificate方法中只有null。
谢谢!