Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidKeyException: Only SecretKey is supported

I have recently started seeing this error in devices.

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)

From https://github.com/justinsb/android-libcore/blob/master/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLCipher.java#L232 exception is thrown when:

if (!(key instanceof SecretKey)) {
   throw new InvalidKeyException("Only SecretKey is supported");
}

I always get my SecretKey from store like this:

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

Any idea what is going on?

like image 912
M-WaJeEh Avatar asked Feb 12 '18 19:02

M-WaJeEh


2 Answers

This happens if key is null.

I had a similar issue, was just a bug in my code which prevented from correctly reading the key. So null was passed in Cipher.init() and caused this message.

like image 175
Jedi-Philosopher Avatar answered Nov 03 '22 06:11

Jedi-Philosopher


Generate Secret Key with Key_Generator Object.

For example:

Initialize SecretKeyObject as Global

SecretKey secretKeyObject;

Initialize the Key Generator Object by:

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();

And then

cipherObject.init(Cipher.ENCRYPT_MODE, secretKeyObject);

This Worked For me.

like image 2
mrcosmic Avatar answered Nov 03 '22 04:11

mrcosmic