InvalidKeyException异常咨询:设备中仅支持SecretKey问题排查
Hey there, sorry you're hitting this frustrating exception—even though you're pulling a SecretKey from storage, there are a few subtle gotchas that can trigger this error. Let's break down the most common causes and things to check:
Accidental type loss during storage/retrieval
Sometimes when reading from KeyStore, if you don't explicitly specify the key type, or if you stored the key by serializing it as a generic object (instead of using KeyStore's standardSecretKeyEntry), the object you get back might logically be a SecretKey, but not the specific implementation class that OpenSSLCipher expects (like Android'sOpenSSLSecretKeyImpl). Add a quick check after retrieval: print the key's actual class name and verify it withinstanceof SecretKeyto rule this out.Mismatched key algorithm and Cipher configuration
A SecretKey isn't enough if its algorithm doesn't align with the Cipher you're initializing. For example, using an AES key with a DES Cipher, or a key length that doesn't match the Cipher's requirements (like a 128-bit AES key when the Cipher is configured for 256-bit). Double-check that the algorithm string you use to create the Cipher (e.g.,"AES/CBC/PKCS5Padding") matches the value returned bysecretKey.getAlgorithm().Incorrect KeyStore entry type
If you're using the system KeyStore or a custom implementation, make sure you're storing the SecretKey as aSecretKeyEntry. Accidentally storing it as aPrivateKeyEntryorTrustedCertificateEntrycan lead to the key being wrapped in a different type when retrieved, even if the underlying key material is correct. Always usekeyStore.setEntry(alias, new SecretKeyEntry(secretKey), protectionParameter)when storing.Cross-process/component key transfer issues
If you're storing the key in one process and reading it in another, or passing it via Intents/Binders, serialization/deserialization can strip away the specific key implementation type. Android's Parcelable doesn't always handle custom SecretKey implementations well. Try to handle key operations within the same process, or use KeyStore's built-in cross-process access capabilities instead of passing the key directly.
Looking at the code you referenced, this exception is thrown during Cipher initialization when the key type fails a check—so the core issue is almost always that the key you're passing isn't the right kind of SecretKey that OpenSSLCipher expects, even if it implements the SecretKey interface.
内容的提问来源于stack exchange,提问作者M-Wajeeh

