A simple Android class for encrypting & decrypting strings
-
Works for strings: It should encrypt arbitrary strings or byte arrays. This means it needs to effectively handle multiple blocks (CBC) and partial blocks (padding). It consistently serializes and deserializes ciphertext, IVs, and key material using base64 to make it easy to store.
-
Algorithm & Mode: We chose: AES 128, CBC, and PKCS5 padding. We would have picked GCM for its built-in integrity checking, but that's only available since Android Jelly Bean.
-
IV Handling: We securely generate a random IV before each encryption and provide a simple class to keep the IV and ciphertext together so they're easy to keep track of and store. We set the IV and then request it back from the Cipher class for compatibility across various Android versions.
-
Key generation: Random key generation with the updated generation code recommended for Android. If you want password-based keys, we provide functions to salt and generate them.
-
Integrity: Lots of people think AES has integrity checking built in. The thinking goes, "if it decrypts correctly, it was generated by the person with the private key". Actually, AES CBC allows an attacker to modify the messages. Therefore, we've also added integrity checking in the form of a SHA 256 hash.
The library is in the Android B4A library format
Dim salt As String : salt = a.saltString(a.generateSalt())
KEY = a.generateKeyFromPassword(EXAMPLE_PASSWORD, salt.GetBytes("UTF8"))
Dim Encryption As Object = a.encrypt(textToEncrpt, KEY)
Dim Decryption As Object = a.decryptString(Encryption, KEY, "UTF-8")