Created
May 20, 2015 14:16
-
-
Save lon9/6946a45684c4a4ca416d to your computer and use it in GitHub Desktop.
Concealを使って文字列を暗号化してPreferenceに保存する。 ref: http://qiita.com/Rompei/items/c21c543707510720db2d
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String getToken(Context context){ | |
SharedPreferences preferences = context.getSharedPreferences(PreferenceValue.PREF_KEY, Context.MODE_PRIVATE); | |
String accessKey = preferences.getString(PreferenceValue.TOKEN_ACCESS_KEY, null); | |
String encryptedToken = preferences.getString(PreferenceValue.ENCRYPTED_KEY, null); | |
byte[] rawEncryptedToken = null; | |
String rawDecryptedToken = null; | |
if(encryptedToken!=null&&accessKey!=null) { | |
rawEncryptedToken = Base64.decode(encryptedToken, Base64.DEFAULT); | |
Crypto crypto = new Crypto( | |
new SharedPrefsBackedKeyChain(context), | |
new SystemNativeCryptoLibrary()); | |
if (!crypto.isAvailable()) { | |
return null; | |
} | |
try { | |
byte[] decryptedToken = crypto.decrypt(rawEncryptedToken, new Entity(accessKey)); | |
rawDecryptedToken = new String(decryptedToken); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} catch (CryptoInitializationException e) { | |
e.printStackTrace(); | |
} catch (KeyChainException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return rawDecryptedToken; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void storeToken(Context context, String token){ | |
SharedPreferences preferences = context.getSharedPreferences(PreferenceValue.PREF_KEY, Context.MODE_PRIVATE); | |
SharedPreferences.Editor editor; | |
String accessKey = UUID.randomUUID().toString(); | |
editor = preferences.edit(); | |
Crypto crypto = new Crypto( | |
new SharedPrefsBackedKeyChain(context), | |
new SystemNativeCryptoLibrary()); | |
if(!crypto.isAvailable()){ | |
return; | |
} | |
try { | |
byte[] encryptedKey = crypto.encrypt(token.getBytes(), new Entity(accessKey)); | |
editor.putString(PreferenceValue.TOKEN_ACCESS_KEY, accessKey); | |
editor.putString(PreferenceValue.ENCRYPTED_KEY, Base64.encodeToString(encryptedKey, Base64.DEFAULT)); | |
}catch (UnsupportedEncodingException e){ | |
e.printStackTrace(); | |
}catch (CryptoInitializationException e){ | |
e.printStackTrace(); | |
}catch(KeyChainException e){ | |
e.printStackTrace(); | |
}catch(IOException e){ | |
e.printStackTrace(); | |
} | |
editor.apply(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment