SlideShare a Scribd company logo
Secure-preferenceshttps://github.com/scottyab/secure-preferences
Jain
Newegg developer
What is
SharedPreferences
• Save and retrieve persistent key-value pairs of
primitive data types
• Save any primitive data: booleans, floats, ints,
longs, and strings
Why use Secure-
preferences
• Protect secret data
1.password
2.token
3.setting
Secure mechanism
• Encrypts the values using AES 128, CBC, and
PKCS5
• Each key is stored as a one way SHA 256 hash
• Both keys and values are base64 encoded before
storing into prefs xml file
Secure data
How to use
public SharedPreferences getSharedPreferences() {
if(mSecurePrefs==null){
mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml");
SecurePreferences.setLoggingEnabled(true);
}
return mSecurePrefs;
}
public SharedPreferences getSharedPreferences1000() {
try {
AesCbcWithIntegrity.SecretKeys myKey =
AesCbcWithIntegrity.generateKeyFromPassword(
Build.SERIAL,AesCbcWithIntegrity.generateSalt(),1000);
return new SecurePreferences(this, myKey, "my_prefs_1000.xml");
} catch (GeneralSecurityException e) {
Log.e(TAG, "Failed to create custom key for SecurePreferences", e);
}
return null;
}
How to use
public SharedPreferences getSharedPreferences() {
if(mSecurePrefs==null){
mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml");
SecurePreferences.setLoggingEnabled(true);
}
return mSecurePrefs;
}
How to use
public SharedPreferences getSharedPreferences() {
if(mSecurePrefs==null){
mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml");
SecurePreferences.setLoggingEnabled(true);
}
return mSecurePrefs;
}
public SharedPreferences getSharedPreferences1000() {
try {
AesCbcWithIntegrity.SecretKeys myKey =
AesCbcWithIntegrity.generateKeyFromPassword(
Build.SERIAL,AesCbcWithIntegrity.generateSalt(),1000);
return new SecurePreferences(this, myKey, "my_prefs_1000.xml");
} catch (GeneralSecurityException e) {
Log.e(TAG, "Failed to create custom key for SecurePreferences", e);
}
return null;
}
public SecurePreferences getUserPinBasedSharedPreferences(String password){
if(mUserPrefs==null) {
mUserPrefs = new SecurePreferences(this, password, "user_prefs.xml");
}
return mUserPrefs;
}
public void onGetButtonClick(View v) {
final String value = getSharedPref().getString(MainActivity.KEY, null);
toast(MainActivity.KEY + "'s, value= " + value);
}
public void onSetButtonClick(View v) {
getSharedPref().edit().putString(MainActivity.KEY, MainActivity.VALUE)
.commit();
toast(MainActivity.KEY + " with enc value:" + MainActivity.VALUE
+ ". Saved");
}
public void onRemoveButtonClick(View v) {
getSharedPref().edit().remove(MainActivity.KEY).commit();
toast("key:" + MainActivity.KEY + " removed from secure prefs");
}
public void onClearAllButtonClick(View v) {
getSharedPref().edit().clear().commit();
updateEncValueDisplay();
toast("All secure prefs cleared");
}
Put value
putString(String key, String value)
hashPrefKey(String prefKey)
encrypt(String cleartext)
encrypt(byte[] plaintext, SecretKeys secretKeys)
new CipherTextIvMac(byteCipherText, iv, integrityMac)
toString()
public static CipherTextIvMac encrypt(byte[] plaintext, SecretKeys secretKeys)
throws GeneralSecurityException {
byte[] iv = generateIv();
Cipher aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION);
aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(iv));
/*
* Now we get back the IV that will actually be used. Some Android
* versions do funny stuff w/ the IV, so this is to work around bugs:
*/
iv = aesCipherForEncryption.getIV();
byte[] byteCipherText = aesCipherForEncryption.doFinal(plaintext);
byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(iv, byteCipherText);
byte[] integrityMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey());
return new CipherTextIvMac(byteCipherText, iv, integrityMac);
}
putString(String key, String value)
hashPrefKey(String prefKey)
encrypt(String cleartext)
encrypt(byte[] plaintext, SecretKeys secretKeys)
new CipherTextIvMac(byteCipherText, iv, integrityMac)
toString()
public String toString() {
String ivString = Base64.encodeToString(iv, BASE64_FLAGS);
String cipherTextString = Base64.encodeToString(cipherText, BASE64_FLAGS);
String macString = Base64.encodeToString(mac, BASE64_FLAGS);
return String.format(ivString + ":" + macString + ":" + cipherTextString);
}
Put value
Get valuegetInt(String key, int defaultValue)
decrypt(final String ciphertext)
new AesCbcWithIntegrity.CipherTextIvMac(ciphertext)
decryptString(cipherTextIvMac, keys)
public static byte[] decrypt(CipherTextIvMac civ, SecretKeys secretKeys)
throws GeneralSecurityException {
byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(civ.getIv(), civ.getCipherText());
byte[] computedMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey());
if (constantTimeEq(computedMac, civ.getMac())) {
Cipher aesCipherForDecryption = Cipher.getInstance(CIPHER_TRANSFORMATION);
aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKeys.getConfidentialityKey(),
new IvParameterSpec(civ.getIv()));
return aesCipherForDecryption.doFinal(civ.getCipherText());
} else {
throw new GeneralSecurityException("MAC stored in civ does not match computed MAC.");
}
}
new String(decrypt(civ, secretKeys), encoding)
Q & A

More Related Content

PDF
The Ring programming language version 1.5.2 book - Part 28 of 181
PDF
The Ring programming language version 1.7 book - Part 32 of 196
PDF
The Ring programming language version 1.5.3 book - Part 29 of 184
PDF
Redis学习笔记
PDF
Offensive PowerShell Cheat Sheet
PPTX
OpenStack Day 2 Operations (Toronto)
PPTX
OpenStack Day 2 Operations
PDF
Managing and Integrating Vault at The New York Times
The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.7 book - Part 32 of 196
The Ring programming language version 1.5.3 book - Part 29 of 184
Redis学习笔记
Offensive PowerShell Cheat Sheet
OpenStack Day 2 Operations (Toronto)
OpenStack Day 2 Operations
Managing and Integrating Vault at The New York Times

What's hot (18)

PDF
The Ring programming language version 1.5.1 book - Part 27 of 180
PDF
Open SSL and MS Crypto API EKON21
DOCX
บทที่6 update&delete
PDF
Elasticsearch security
PPT
Learning Java 4 – Swing, SQL, and Security API
PDF
The Ring programming language version 1.6 book - Part 31 of 189
PPT
Wicket Security Presentation
PDF
Given Groovy Who Needs Java
PDF
The Ring programming language version 1.5.4 book - Part 29 of 185
PDF
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
PPTX
iOS Keychain 介紹
PDF
Black Hat Europe 2017. DPAPI and DPAPI-NG: Decryption Toolkit
PPTX
Socket.io v.0.8.3
DOCX
Update&delete
PDF
The Ring programming language version 1.3 book - Part 17 of 88
PDF
201913001 khairunnisa progres_harian
DOCX
Fia fabila
PPTX
Code refactoring of existing AutoTest to PageObject pattern
The Ring programming language version 1.5.1 book - Part 27 of 180
Open SSL and MS Crypto API EKON21
บทที่6 update&delete
Elasticsearch security
Learning Java 4 – Swing, SQL, and Security API
The Ring programming language version 1.6 book - Part 31 of 189
Wicket Security Presentation
Given Groovy Who Needs Java
The Ring programming language version 1.5.4 book - Part 29 of 185
Amazon Cognito使って認証したい?それならSpring Security使いましょう!
iOS Keychain 介紹
Black Hat Europe 2017. DPAPI and DPAPI-NG: Decryption Toolkit
Socket.io v.0.8.3
Update&delete
The Ring programming language version 1.3 book - Part 17 of 88
201913001 khairunnisa progres_harian
Fia fabila
Code refactoring of existing AutoTest to PageObject pattern
Ad

Viewers also liked (20)

PDF
Keynote Address by Marc Stoiber - Ready! Fire! Aim!
DOCX
Guión diseño instruccional.docx
KEY
讀書樂無窮
PDF
Untitled Presentation
PDF
logo new feb 2015
PDF
Lo importante no es tener sino trascender
PPTX
Presentation_NEW.PPTX
PPT
Subj.verb agreement
PDF
Take Advantage of Mobile Marketing to Build Business Success
DOC
Resume Hordych 2014 - AD
PPTX
Boxtream tools-161106062349
DOC
CV. in inglish
PPTX
Question 7
PDF
Rita tria how to use ifttt
PPTX
Powerful Goal Setting Strategies
PDF
【行銷策略】七大提升廣告效益的實戰祕訣
PDF
La Toma de Decisiones en las Escuelas ccesa007
PDF
Hacking With Sql Injection Exposed - A Research Thesis
PDF
Innovaciones en Gestión Educativa ccesa007
PDF
Natalia Hatalska, Alternatywne formy reklamy, konferencja I ♥ Marketing, 25....
Keynote Address by Marc Stoiber - Ready! Fire! Aim!
Guión diseño instruccional.docx
讀書樂無窮
Untitled Presentation
logo new feb 2015
Lo importante no es tener sino trascender
Presentation_NEW.PPTX
Subj.verb agreement
Take Advantage of Mobile Marketing to Build Business Success
Resume Hordych 2014 - AD
Boxtream tools-161106062349
CV. in inglish
Question 7
Rita tria how to use ifttt
Powerful Goal Setting Strategies
【行銷策略】七大提升廣告效益的實戰祕訣
La Toma de Decisiones en las Escuelas ccesa007
Hacking With Sql Injection Exposed - A Research Thesis
Innovaciones en Gestión Educativa ccesa007
Natalia Hatalska, Alternatywne formy reklamy, konferencja I ♥ Marketing, 25....
Ad

Similar to Secure preferences (20)

PDF
Develop an encryption and decryption algorithm Your program should a.pdf
PDF
ERRest
PDF
Whispered secrets
PPT
Java Symmetric
PDF
Encryption Boot Camp at JavaZone 2010
PPTX
Secureerasurecodebasedcloudstoragesystemwithsecuredataforwarding
PPTX
Secure erasure code based cloud storage system with secure data forwarding
PPTX
Django cryptography
PPTX
PDF
iOS Keychain by 흰, 민디
PPTX
Cargo Cult Security UJUG Sep2015
PDF
Configuration beyond Java EE 8
PPTX
Cryptography 101 for Java developers
PDF
React Native Course - Data Storage . pdf
PDF
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
PPTX
Cryptography In Silverlight
PPTX
Hadoop Puzzlers
PPTX
Hadoop Puzzlers
PDF
Secure .NET programming
PDF
Refactoring In Tdd The Missing Part
Develop an encryption and decryption algorithm Your program should a.pdf
ERRest
Whispered secrets
Java Symmetric
Encryption Boot Camp at JavaZone 2010
Secureerasurecodebasedcloudstoragesystemwithsecuredataforwarding
Secure erasure code based cloud storage system with secure data forwarding
Django cryptography
iOS Keychain by 흰, 민디
Cargo Cult Security UJUG Sep2015
Configuration beyond Java EE 8
Cryptography 101 for Java developers
React Native Course - Data Storage . pdf
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menace
Cryptography In Silverlight
Hadoop Puzzlers
Hadoop Puzzlers
Secure .NET programming
Refactoring In Tdd The Missing Part

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPT
Teaching material agriculture food technology
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
A Presentation on Artificial Intelligence
PPTX
Cloud computing and distributed systems.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
NewMind AI Weekly Chronicles - August'25-Week II
Teaching material agriculture food technology
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Chapter 3 Spatial Domain Image Processing.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
Empathic Computing: Creating Shared Understanding
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine Learning_overview_presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Assigned Numbers - 2025 - Bluetooth® Document
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
MYSQL Presentation for SQL database connectivity
20250228 LYD VKU AI Blended-Learning.pptx
sap open course for s4hana steps from ECC to s4
A Presentation on Artificial Intelligence
Cloud computing and distributed systems.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction

Secure preferences

  • 2. What is SharedPreferences • Save and retrieve persistent key-value pairs of primitive data types • Save any primitive data: booleans, floats, ints, longs, and strings
  • 3. Why use Secure- preferences • Protect secret data 1.password 2.token 3.setting
  • 4. Secure mechanism • Encrypts the values using AES 128, CBC, and PKCS5 • Each key is stored as a one way SHA 256 hash • Both keys and values are base64 encoded before storing into prefs xml file
  • 6. How to use public SharedPreferences getSharedPreferences() { if(mSecurePrefs==null){ mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml"); SecurePreferences.setLoggingEnabled(true); } return mSecurePrefs; }
  • 7. public SharedPreferences getSharedPreferences1000() { try { AesCbcWithIntegrity.SecretKeys myKey = AesCbcWithIntegrity.generateKeyFromPassword( Build.SERIAL,AesCbcWithIntegrity.generateSalt(),1000); return new SecurePreferences(this, myKey, "my_prefs_1000.xml"); } catch (GeneralSecurityException e) { Log.e(TAG, "Failed to create custom key for SecurePreferences", e); } return null; } How to use public SharedPreferences getSharedPreferences() { if(mSecurePrefs==null){ mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml"); SecurePreferences.setLoggingEnabled(true); } return mSecurePrefs; }
  • 8. How to use public SharedPreferences getSharedPreferences() { if(mSecurePrefs==null){ mSecurePrefs = new SecurePreferences(this, "", "my_prefs.xml"); SecurePreferences.setLoggingEnabled(true); } return mSecurePrefs; } public SharedPreferences getSharedPreferences1000() { try { AesCbcWithIntegrity.SecretKeys myKey = AesCbcWithIntegrity.generateKeyFromPassword( Build.SERIAL,AesCbcWithIntegrity.generateSalt(),1000); return new SecurePreferences(this, myKey, "my_prefs_1000.xml"); } catch (GeneralSecurityException e) { Log.e(TAG, "Failed to create custom key for SecurePreferences", e); } return null; } public SecurePreferences getUserPinBasedSharedPreferences(String password){ if(mUserPrefs==null) { mUserPrefs = new SecurePreferences(this, password, "user_prefs.xml"); } return mUserPrefs; }
  • 9. public void onGetButtonClick(View v) { final String value = getSharedPref().getString(MainActivity.KEY, null); toast(MainActivity.KEY + "'s, value= " + value); } public void onSetButtonClick(View v) { getSharedPref().edit().putString(MainActivity.KEY, MainActivity.VALUE) .commit(); toast(MainActivity.KEY + " with enc value:" + MainActivity.VALUE + ". Saved"); } public void onRemoveButtonClick(View v) { getSharedPref().edit().remove(MainActivity.KEY).commit(); toast("key:" + MainActivity.KEY + " removed from secure prefs"); } public void onClearAllButtonClick(View v) { getSharedPref().edit().clear().commit(); updateEncValueDisplay(); toast("All secure prefs cleared"); }
  • 10. Put value putString(String key, String value) hashPrefKey(String prefKey) encrypt(String cleartext) encrypt(byte[] plaintext, SecretKeys secretKeys) new CipherTextIvMac(byteCipherText, iv, integrityMac) toString() public static CipherTextIvMac encrypt(byte[] plaintext, SecretKeys secretKeys) throws GeneralSecurityException { byte[] iv = generateIv(); Cipher aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION); aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(iv)); /* * Now we get back the IV that will actually be used. Some Android * versions do funny stuff w/ the IV, so this is to work around bugs: */ iv = aesCipherForEncryption.getIV(); byte[] byteCipherText = aesCipherForEncryption.doFinal(plaintext); byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(iv, byteCipherText); byte[] integrityMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey()); return new CipherTextIvMac(byteCipherText, iv, integrityMac); }
  • 11. putString(String key, String value) hashPrefKey(String prefKey) encrypt(String cleartext) encrypt(byte[] plaintext, SecretKeys secretKeys) new CipherTextIvMac(byteCipherText, iv, integrityMac) toString() public String toString() { String ivString = Base64.encodeToString(iv, BASE64_FLAGS); String cipherTextString = Base64.encodeToString(cipherText, BASE64_FLAGS); String macString = Base64.encodeToString(mac, BASE64_FLAGS); return String.format(ivString + ":" + macString + ":" + cipherTextString); } Put value
  • 12. Get valuegetInt(String key, int defaultValue) decrypt(final String ciphertext) new AesCbcWithIntegrity.CipherTextIvMac(ciphertext) decryptString(cipherTextIvMac, keys) public static byte[] decrypt(CipherTextIvMac civ, SecretKeys secretKeys) throws GeneralSecurityException { byte[] ivCipherConcat = CipherTextIvMac.ivCipherConcat(civ.getIv(), civ.getCipherText()); byte[] computedMac = generateMac(ivCipherConcat, secretKeys.getIntegrityKey()); if (constantTimeEq(computedMac, civ.getMac())) { Cipher aesCipherForDecryption = Cipher.getInstance(CIPHER_TRANSFORMATION); aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKeys.getConfidentialityKey(), new IvParameterSpec(civ.getIv())); return aesCipherForDecryption.doFinal(civ.getCipherText()); } else { throw new GeneralSecurityException("MAC stored in civ does not match computed MAC."); } } new String(decrypt(civ, secretKeys), encoding)
  • 13. Q & A