InvalidKeyException:仅支持SecretKey

M-W*_*eEh 8 security encryption ssl android boringssl

我最近开始在设备中看到此错误。

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)
Run Code Online (Sandbox Code Playgroud)

在以下 情况下,从https://github.com/justinsb/android-libcore/blob/master/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLCipher.java#L232引发异常

if (!(key instanceof SecretKey)) {
   throw new InvalidKeyException("Only SecretKey is supported");
}
Run Code Online (Sandbox Code Playgroud)

我总是这样从商店获取我的SecretKey:

SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
Run Code Online (Sandbox Code Playgroud)

知道发生了什么吗?

小智 2

使用 Key_Generator 对象生成密钥。

例如:

将 SecretKeyObject 初始化为全局

SecretKey secretKeyObject;
Run Code Online (Sandbox Code Playgroud)

通过以下方式初始化密钥生成器对象:

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();
Run Code Online (Sandbox Code Playgroud)

进而

cipherObject.init(Cipher.ENCRYPT_MODE, secretKeyObject);
Run Code Online (Sandbox Code Playgroud)

这对我有用。