在调用KeyGenerator前,需要先通过KeyPairGenerator初始化Provider,例如:
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .setUserAuthenticationRequired(true) .setUserAuthenticationValidityDurationSeconds(120) .build();
KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); kpGenerator.initialize(keyGenParameterSpec); kpGenerator.generateKeyPair();
这样可以先初始化Provider,避免KeyGenerator返回ProviderException异常。
上一篇:AndroidKeyGenerator返回ProviderException
下一篇:AndroidKeyguardManager中的isDeviceLocked和isKeyguardLocked有什么区别?