encryption - Android: Store SecretKey in KeyStore -
i use secretkey encrypt sensitive data in application. storing secretkey in base64 encoded format in db or sharedprefs not safe place store secret on rooted phone. hence, want move secretkey android keystore. problem facing when try this sample code google, expects privatekey instead of secretkey. couldn't figure out way store secretkey in keystore , fetch later use. tried this:
private static void writesecretkeytokeystore(secretkey secretkey, context context) { keystore keystore = null; try { keystore = keystore.getinstance("androidkeystore"); keystore.load(null); keystore.secretkeyentry secretkeyentry = new keystore.secretkeyentry(secretkey); keystore.setkeyentry("key", secretkeyentry.getsecretkey().getencoded(), null); } catch (keystoreexception e) { e.printstacktrace(); } catch (certificateexception e) { e.printstacktrace(); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); }
when try above code, throws exception operation not supported because encoding unknown
.
any sample code of great help.
wrong
java.security.keystore can store both symmetric , asymmetric keys. need instantiate keystore.secretkeyentry passing secretkey in constructor , use keystore#setentry method save it:
keystore.setentry( "key1", new keystore.secretkeyentry(secretkey), new keyprotection.builder(keyproperties.purpose_encrypt | keyproperties.purpose_decrypt) .setblockmode(keyproperties.block_mode_gcm) .setencryptionpaddings(keyproperties.encryption_padding_none) .build());
to out use:
secretkey keystorekey = (secretkey) keystore.getkey("key1", null);
update
after research surprised find out, androidkeystore doesn't support symmetric keys. (see discussion: https://groups.google.com/forum/#!topic/android-developers/gbmirkrbfq8)
Comments
Post a Comment