如果您在使用Android KeyStore时遇到了KM_ERROR_UNKNOWN_ERROR错误,请参考以下示例代码来解决此问题:
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null);
// 插入密钥的字节数组 byte[] keyData = ...;
// 密钥别名 String keyAlias = "my_key";
// 密钥规范 KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setRandomizedEncryptionRequired(false) .build();
// 密钥生成器 KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); generator.init(spec);
// 生成密钥 generator.generateKey();
// 获取密钥 SecretKey secretKey = (SecretKey) keyStore.getKey(keyAlias, null);
// 导入密钥 KeyFactory keyFactory = KeyFactory.getInstance(secretKey.getAlgorithm(), "AndroidKeyStore"); KeyInfo keyInfo = keyFactory.getKeySpec(secretKey, KeyInfo.class); KeymasterArguments args = new KeymasterArguments(); args.addUnsignedLong(KeymasterDefs.KM_TAG_KEY_SIZE, (long) keyInfo.getKeySize());
KeymasterBlob keyBlob = new KeymasterBlob(keyData);
int errorCode = KeyStoreCompat.getInstance().importKey( keyAlias, keyBlob, KeyProperties.KEY_ALGORITHM_AES, KeyStoreCompat.ENUMERATE_NONE, args, KeyStoreCompat.USE_DEFAULT_TIMEOUT, null);
if (errorCode == KeyStoreCompat.KM_ERROR_OK) { // 导入密钥成功 } else { // 导入密钥失败 }