Using all the methods discussed in the earlier sections, you can now encrypt any information in your application, as shown in the following code:
String myData = "My secret information"; SecretKeySpec sks = generateKey(); byte[] encoded = encrypt(myData, sks); String decoded = decrypt(encoded, sks); Log.d("MAIN - Encoded: ", Base64.encodeToString(encoded, Base64.DEFAULT)); Log.d("MAIN - Decoded: ", decoded);
The results generated in LogCat are shown in the following screenshot:
The previous example can be adapted to encrypt the content of a file on the internal storage of your application, as shown in the following code:
String myData = "My secret information in my internal file"; SecretKeySpec sks = generateKey(); byte[] encoded = encrypt(myData, sks); FileOutputStream fos = openFileOutput("MyEncryptedFile.txt", Context.MODE_PRIVATE); fos.write(encoded); fos.close();
On executing the code in your main activity, the MyEncryptedFile.txt
file will be created...