The Android docs give the following snippet for how to encrypt a message in AES:
val plaintext: ByteArray = ...
val keygen = KeyGenerator.getInstance("AES")
keygen.init(256)
val key: SecretKey = keygen.generateKey()
val cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING")
cipher.init(Cipher.ENCRYPT_MODE, key)
val ciphertext: ByteArray = cipher.doFinal(plaintext)
val iv: ByteArray = cipher.iv
I get this error when implementing this method:
Unresolved reference: Cipher
So it appears the ‘Cipher’ object isn’t native, however I have no way of knowing how to import it by following the Android docs. How do I set up my project to be able to use ‘Cipher’?
2
Answers
I’m not sure if using that
Cipher
is necessary, and if the solution I’m providing is the best approach, but I was able to useAES
forencryption
anddecryption
using the following code for atext
input, means aString
:ENCRYPTION
DECRYPTION
You must save the
key
,initialisation vector
, and theencrypted text
in order to decrypt it back.EDIT
AES helper class:
AES decrypt helper
Do tell if you still need any help 🙂
javax.crypto.Cipher
is part of the JCE and should be available. Does an importjavax.crypto.Cipher
not work? Then maybe something is wrong with your environment.