InvalidKeyException:仅支持SecretKey

时间:2018-02-12 19:45:34

标签: android security ssl encryption 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)

来自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");
}

我总是从商店里得到我的SecretKey:

SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);

知道发生了什么事吗?

2 个答案:

答案 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并导致了此消息。