I am making an android application that communicates with a server. I'm using token based authentication on my server, and to pass information to the client from the server, I am using asymmetric encryption.
This is how the process goes
- Generated public and private key already exists before hand
- Public key is used to encrypt information, and then passed from server to client
- App uses private key to decrypt information
However, I do not know how to securely store the private key in the keystore. If I store it during runtime, the key will be out in the code, and if I send the private key during the REST connection, then there's no point of having the encryption because a hacker can find both keys. Can anyone help me on creating the best possible solution? THX in advance!
You can store your private key in shared preferences, but encrypted with generated secret key, which will be stored in Android
KeyStore
, which will give much more security in storing the private key.Please see example below in Kotlin. First, you need to generate secret key:
It will be automatically stored in the
KeyStore
since we're mentioning it as a provider when getting instance of aKeyGenerator
.Later, when you will need to obtain secret key again you can do it like this:
Or you can always use
getSecretKey()
method, which will generate new one if the obtained from theKeyStore
isnull
by changing last line to:When
SecretKey
is obtained you can proceed with encryption:Here, method
encrypt
will return aByteArray
that you can store in theSharedPreferences
. NOTE: that you should also store initialization vector (IV). Here it is stored to theiv
property.To decrypt stored data, use this method:
Here, you must pass store initialization vector (IV) to
GCMParameterSpec
.Hope it will helps someone.