下面的最小示例(一次调用)在我的Motorola G6上阻止了UI。它出什么问题了?密钥库是否在幕后某个地方的主线程上执行某些操作? (编辑:我怀疑是RAM问题。将RSA密钥大小更改为2048后,它会好得多,尽管UI暂停仍然很小)
Observable.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, new SecureRandom());
Key key = generator.generateKey();
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.add(Calendar.YEAR, 100);
KeyStore.getInstance("AndroidKeyStore").load(null);
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
.setAlias("some_id")
.setKeySize(3072)
.setKeyType(KeyProperties.KEY_ALGORITHM_RSA)
.setStartDate(start.getTime())
.setEndDate(end.getTime())
.setSerialNumber(BigInteger.ONE)
.setSubject(new X500Principal("CN = Secured Preference Store, O = Some Name"))
.build();
keyGen.initialize(spec);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey rsaPublicKey = keyPair.getPublic();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
cipherOutputStream.write(key.getEncoded());
cipherOutputStream.close();
return true;
}
}).subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).subscribe();