android


Android KeyStore to store the SecretKey for encryption/decryption


I am trying to have secret (String) in the app, anywhere, save to be! So I came up with this idea to use the keyStore to store the key and only use it for encryption and decryption of my secret. Here is how I save (encrypt) my secret:
public static boolean setKeyStoreString(String strToStore, Context context) {
if (strToStore == null) return false;
if (strToStore.length() == 0) return false;
Log.e(TAG, strToStore);
try {
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
int nBefore = keyStore.size();
// Create the keys if necessary
if (!keyStore.containsAlias("phrase")) {
KeyGenerator generator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder("phrase", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setKeySize(256)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationValidityDurationSeconds(-1)
.setRandomizedEncryptionRequired(false)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.setUserAuthenticationRequired(false)
.build();
generator.init(spec);
generator.generateKey();
}
int nAfter = keyStore.size();
Log.v(TAG, "Before = " + nBefore + " After = " + nAfter);
String filesDirectory = context.getFilesDir().getAbsolutePath();
String encryptedDataFilePath = filesDirectory + File.separator + "my_phrase";
// Log.v(TAG, "strPhrase = " + strToStore);
// Log.v(TAG, "dataDirectory = " + dataDirectory);
// Log.v(TAG, "filesDirectory = " + filesDirectory);
// Log.v(TAG, "encryptedDataFilePath = " + encryptedDataFilePath);
SecretKey secret = (SecretKey) keyStore.getKey("phrase", null);
Cipher inCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
inCipher.init(Cipher.ENCRYPT_MODE, secret);
CipherOutputStream cipherOutputStream = new CipherOutputStream(
new FileOutputStream(encryptedDataFilePath), inCipher);
byte[] bytesToStore = strToStore.getBytes("UTF-8");
cipherOutputStream.write(bytesToStore);
try {
cipherOutputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return true;
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
}
return false;
}
and here is how I try to retrieve it:
public static String getKeyStoreString(final Context context) {
KeyStore keyStore;
String recoveredSecret = "";
String filesDirectory = context.getFilesDir().getAbsolutePath();
String encryptedDataFilePath = filesDirectory + File.separator + "my_phrase";
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
SecretKey secretKey = (SecretKey)
keyStore.getKey("phrase", null);
if (secretKey == null) throw new RuntimeException("secretKey is null");
Cipher outCipher;
outCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
outCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(
new byte[outCipher.getBlockSize()]));
CipherInputStream cipherInputStream = new CipherInputStream(
new FileInputStream(encryptedDataFilePath), outCipher);
byte[] roundTrippedBytes = new byte[1000]; //TODO: dynamically resize as we get more data
int index = 0;
int nextByte;
while ((nextByte = cipherInputStream.read()) != -1) {
roundTrippedBytes[index] = (byte) nextByte;
index++;
}
recoveredSecret = new String(roundTrippedBytes, 0, index, "UTF-8");
Log.e(TAG, "round tripped string = " + recoveredSecret);
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "recovered: " + recoveredSecret);
return recoveredSecret;
}
the problem is - the result comes a little damaged in the beginning,
i.e: some cool text for extraction >>>>> �k��X�&�ALqM,A� text for
extraction
i have the same problem i used Base64.encode(your byte[], Base64.DEFAULT);to encode and Base64.decode(your byte[], Base64.DEFAULT) to decode
try to put byte[] encode = Base64.encode(bytesToStore, Base64.DEFAULT)
after byte[] bytesToStore = strToStore.getBytes("UTF-8");
in the public static boolean setKeyStoreString() and check in the "encode" log

Related Links

How to detect mail client : desktop or mobile, and platform if mobile?
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
How to restrict EditText to two lines in android
image attach option is not coming after taking image from camera
ViewFlipper with only 1 layout?
No item in ListView
Can we access at a time Camera in multiple application?
How are call types (Incoming/Outgoing/Missed) stored in Android Call Log?
extracting json from a website
Error giving during compilation in release mode
Android : image size defining
read data content in TableRow
Element in layout isn't showing up (covered up by another element)
Android project library not refreshing?
Add a contact to the mobile device Address book from an HTML webpage
Android c2dm 302 Http error

Categories

HOME
url-redirection
embedded
checkstyle
merge
webdriver
static
spring-session
google-cloud-datalab
mvc5
trac
mql5
pcl-crypto
commonjs
fhir
mautic
openbugs
zerobrane
docx
azure-iot-hub
esoteric-languages
chargify
foreign-keys
sigma.js
topology
kendo-mobile
imagemap
r-mice
imageresizer
exploit
onload
android-sharedpreferences
datastax-enterprise-graph
anki
scatter3d
cognos-bi
angularjs-material
r-grid
mailkit
classcastexception
sql-delete
python-pptx
google-earth-engine
unordered-map
stringtokenizer
dcmtk
portforwarding
preloader
print-css
http-request
tcc
procfile
puredata
openblas
reindex
appdomain
boxing
sundials
arules
cpu-cache
gets
qtplugin
flex4.6
resourcemanager
signalr.client
x-tag
tooleap
google-query-language
thread-sleep
jnlua
directdraw
forwarding
google-books
phonertc
ocra
keyup
canvg
entity-framework-4.3
filesplitting
nsmenu
mintty
live555
alternate
dot42
terminate
gtm-oauth2
away3d
process-explorer
pclzip
joomla3.1
panda3d
zope.interface
iboutlet
luabind
procedures
expression-blend-4
collectionviewsource
facebook-iframe
message-passing
tabpanel
feasibility
wordprocessingml
windows-identity
int64
flvplayback

Resources

Encrypt Message