Android Keystore
In this post we will learn how to store a key in android provider keystore and encrypt and decrypt.
In this post we will learn how to store a key in android provider keystore and encrypt and decrypt.
Keystore
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
SecretKey key = new SecretKeySpec(keyByte, alg);
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(key);
// store key in keystore
ks.setEntry(
"keyName",
new KeyStore.SecretKeyEntry(secretKeyEntry.getSecretKey()),
new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build());
// get key from key store
SecretKey keyStoreKey = (SecretKey) ks.getKey("keyName", null);
Encryption
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, keyStoreKey);
byte[] encryptedByte = cipher.doFinal("Hello World".getByte());
Decryption
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(128, cipher.getIV());
cipher.init(Cipher.DECRYPT_MODE, keyStoreKey, spec);
byte[] decryptedByte = cipher.doFinal(encryptedByte);
Comments
Post a Comment