Your Order for encrypt: getBytes, encrypt, encode, toString
Your Order for decrypt(Wrong*): getBytes, decrypt, decode, toString
Two problems:
- As someone already mentioned you should reverse the order of operations for decryption. You are not doing that.
- encrypt gives you 16 bytes, encode 24 bytes, but toString gives 106 bytes. Something to do with invalid chars taking up additional space.
Note: Also, you don't need to call generateKey()
twice.
Fix problem #1 by using the reverse order for decryption.
Correct order for decrypt: getBytes, decode, decrypt, toString
Fix problem #2 by replacing xxx.toString()
with new String(xxx)
. Do this in both the encrypt and decrypt functions.
Your decrypt should look like this:
c.init(Cipher.DECRYPT_MODE, key)
val decodedValue = new Base64().decode(encryptedValue.getBytes())
val decryptedVal = c.doFinal(decodedValue)
return new String(decryptedVal)
This should give you back "dude5"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…