July 29, 2021

Android Keystore based Encryption and Decryption in Xamarin Android

Brief Walkthrough on Android Keystore based app security in Xamarin android

Description
Data security should be considered as  top priority in any application and this is not just for password any sensitive data, app internal files including the database file. Any security breach in app secret data or app unique concepts(USP) can make way to competitors/attackers.  There are plenty of approaches one can choose to secure app private data.

Why Android Keystore based security : In general in any data encryption/decryption we need to provide the public/private keys. here the challenge is how we can secure these keys. Keystore based security provides solution for this issue where it generates and maintains the key dynamically. 


Let us get into the coding part:
Create Secret key:
  • Choose the alias name which is any non empty string to identify the key saved in keystore. 
  • Create an instance of AndroidKeyStore where it saves the key and it generates the key only if it is not created already.
  • Specify the algorithm used with keyGenerator and the purpose of the key used for i.e. encryption and decryption.
  • Specify the BlockModes that is going to use for encryption and decryption operation.
Encrypt:
For encrption i have taken two examples:
1.File encryption it can be any file in device internal/external storage database file.
2.Plain text encryption, password or any string before saving to DB or sync.

1.File Encryption:
For file encrption just pass the existing file path and destination path where you want to save the encrypted file. (If you are encrypting and decrypting DB file then need to ensure that DB connections are closed)
  • Get the secret key by calling above mentioned method
  • Create the instance of Cipher by mentioning encryption type
  • Save the initialization vector(iv) from cipher which is going to use in decryption
  • Pass the bytes of source file to DoFinal method of cipher which returns bytes which is in encrypted format, save that bytes in destination file path
  • After encryption delete the original file

Decrypt:
  • In the same way as encryption get the secret key. 
  • Use the initialization vector which is already generated to create the GCMParameterSpec.
  • Here source file path points to the file created after above encryption process.
  • DoFinal method returns the bytes which is saved in destination file path and the decryped file.

2.String encryption and decryption:
Here the same steps will be followed as in file encryption/decryption except file path actual string is passed to encryption method and decryption method returns the string in original format nothing but decrypted string.
 

And we are done! Happy coding.

No comments:

Post a Comment