我最近开始在设备中看到此错误。
java.security.InvalidKeyException: Only SecretKey is supported
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:436)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:273)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:2664)
at javax.crypto.Cipher.tryCombinations(Cipher.java:2575)
at javax.crypto.Cipher$SpiAndProviderUpdater.updateAndGetSpiAndProvider(Cipher.java:2480)
at javax.crypto.Cipher.chooseProvider(Cipher.java:567)
at javax.crypto.Cipher.init(Cipher.java:975)
at javax.crypto.Cipher.init(Cipher.java:910)
if (!(key instanceof SecretKey)) {
throw new InvalidKeyException("Only SecretKey is supported");
}
我总是从商店里得到我的SecretKey:
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
知道发生了什么事吗?
答案 0 :(得分:0)
使用Key_Generator对象生成秘密密钥。
例如:
将SecretKeyObject初始化为全局
SecretKey secretKeyObject;
通过以下方式初始化密钥生成器对象:
KeyGenerator keyGeneratorObject = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore");
keyStoreObject.load(null);
keyGeneratorObject.init(new KeyGenParameterSpec.Builder(key_name,KeyProperties.PURPOSE_ENCRYPT|KeyProperties.PURPOSE_DECRYPT).setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build());
secretKeyObject = keyGeneratorObject.generateKey();
然后
cipherObject.init(Cipher.ENCRYPT_MODE, secretKeyObject);
这对我有用。
答案 1 :(得分:0)
如果key为null,则会发生这种情况。
我有一个类似的问题,只是我的代码中的一个错误导致无法正确读取密钥。因此,在Cipher.init()中传递了null并导致了此消息。