SlideShare a Scribd company logo
1 of 56
Download to read offline
Android 
Key Management 
Roberto Piccirillo (r.piccirillo@mseclab.com) 
Roberto Gassirà (r.gassira@mseclab.com) 
Droidcon 
London 2014
Roberto Piccirillo 
● Senior Security Analyst - Mobile Security Lab 
○ Vulnerability Assessment (IT, Mobile Application) 
○ Hijacking Mobile Data Connection 
■ BlackHat Europe 2009 
■ DeepSec Vienna 2009 
■ HITB Amsterdam 2010 
○ Android Secure Development 
● GDG Rome Lab 
@robpicone 
Android 
Key Management Droidcon London 2014
Roberto Gassirà 
● Senior Security Analyst - Mobile Security Lab 
○ Vulnerability Assessment (IT, Mobile Application) 
○ Hijacking Mobile Data Connection 
■ BlackHat Europe 2009 
■ DeepSec Vienna 2009 
■ HITB Amsterdam 2010 
○ Android Secure Development 
● GDG Rome Lab 
@robgas 
Android 
Key Management Droidcon London 2014
Android Key Management: Agenda 
● Mobile Application Cryptography 
● Key Management and CryptoSystem 
● Crypto in Android 
● Symmetric Encryption 
● Symmetric Key Management 
● Asymmetric key: Encryption/Digital Signature 
● Keychain e AndroidKeyStore 
Android 
Key Management Droidcon London 2014
Mobile Application Cryptography 
➢ Protect Data: 
○ Sensitive Data 
○ Backup on /sdcard 
➢ Exchange data securely: 
Android 
Key Management Droidcon London 2014
Key Management 
"Key management is the management of cryptographic keys in a 
cryptosystem." 
Android 
Key Management Droidcon London 2014
CryptoSystem 
"refers to a suite of algorithms needed to implement a particular 
form of encryption and decryption" 
● Two types of encryption: 
○ Symmetric Key Algorithms 
■ Identical key for 
encryption/decryption 
■ AES, Blowfish, DES, Triple DES 
○ Asymmetric Key Algorithms 
■ Pair of keys (public/private) for 
encryption/decryption 
■ RSA, DSA, ECDSA 
Android 
Key Management Droidcon London 2014
Symmetric Key Algorithms: Ciphers 
● Two types of ciphers: 
○ Block: Process entire blocks of fixed-length 
groups of bits at a time (padding may be 
required) 
○ Stream: Process single bit at a time(no 
padding) 
● Block Cipher modes of operation: 
○ ECB: each block encrypted independently 
○ CBC, CFB, OFB: (feedback mode) each block 
is encrypted combined with the previous 
encrypted block (starting from an IV) 
○ CTR: each block xored with the encrypted 
successive values of a counter ( starting 
from a nonce) 
ECB 
CBC 
Android 
Key Management Droidcon London 2014
Crypto in Android 
● Framework based on JCA ( Java 
Cryptography Architecture) 
● Provides API for: 
● Encryption/Decryption 
● Message digests (hashes) 
● Key management 
● Secure random number generation 
● API implemented by Cryptographic 
Service "Provider" 
● "Dynamic" Provider: 
javax.crypto.* 
java.security.* 
Android 
Key Management Droidcon London 2014
Default Providers 
➢ From the beginning 
○ Bouncy Castle (Customized): 
■ Some services and API removed 
■ Varies between Android versions 
■ Fixed only in the latest versions 
○ Crypto (Apache Harmony) 
■ Few basic services 
■ Only for backward compatibility 
➢ From Android 4.0 
○ AndroidOpenSSL: 
■ OpenSSL JNI 
■ Performance Improved 
■ Vulnerable to Heartbleed in 4.1.1 
Android 
Key Management Droidcon London 2014
➢ Spongy Castle (SC) 
Dynamic Providers 
○ Repackage of Bouncy Castle 
○ Supports more cryptographic options 
○ Not vulnerable to the Heartbleed Bug 
○ Up-to-date 
➢ GPS Dynamic Security Provider 
○ Available from Play Services 5.0 
○ Based on OpenSSL ( No Heartbleed) 
○ Rapid delivery of security patches 
○ Vendor independent !!! 
Android 
Key Management Droidcon London 2014
Cipher Benchmarks 
CBC CTR 
Run on Google Nexus 5 Android 4.4.4 
Android 
Key Management Droidcon London 2014
Cipher Class 
Secret Key Specification 
Cipher getInstance 
Cipher Init 
Cipher Final 
Android 
Key Management Droidcon London 2014
SecretKey Specification 
javax.crypto.spec.SecretKeySpec 
● SecretKeySpec specifies a key for a specific algorithm 
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); 
Encryption/Decryption 
Key 
Cryptographic Algorithm 
Android 
Key Management Droidcon London 2014
Cipher GetInstance 
javax.crypto.Cipher 
● Create cryptographic cipher 
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding”,“SC”); 
Transformation 
(describes set of operation to 
perform): 
• algorithm/mode/padding 
• algorithm 
Provider 
( SpongyCastle ) 
Android 
Key Management Droidcon London 2014
Cipher Init 
javax.crypto.Cipher 
● Initializes the cipher instance with the specified operational 
mode, key and algorithm parameters. 
cipher.init(Cipher.DECRYPT_MODE, keySpec, 
new IvParameterSpec(iv)); 
Operational Mode: 
• ENCRYPT_MODE 
• DECRYPT_MODE 
• WRAP_MODE 
• UNWRAP_MODE 
SecretKeySpec Specify Cipher 
Algorithm parameters 
( IV for CBC ) 
Android 
Key Management Droidcon London 2014
Cipher Final 
javax.crypto.Cipher 
● Complete a multi-part transformation (encryption or 
decryption) 
byte[] encryptedText = cipher.doFinal(clearText.getBytes()); 
Encrypted 
Text in byte 
ClearText in 
bytes 
Android 
Key Management Droidcon London 2014
Key Generation: SecureRandom 
java.security.SecureRandom 
● Cryptographically secure pseudo-random number generator 
SecureRandom secureRandom = new SecureRandom(); 
Default constructor uses the 
most cryptographically 
strong provider available 
● Seeding 
SecureRandom is 
dangerous: 
○ Not Secure 
○ Output may change 
Android 
Key Management Droidcon London 2014
Some SecureRandom Thoughts... 
http://android-developers.blogspot.it/2013/08/some-securerandom-thoughts.html 
● Android security team discovered in August 2013 an improper 
PRNG initialization for default OpenSSL provider 
● Applications invoking system-provided OpenSSL PRNG without 
explicit initialization are also affected 
● Key Generation, Signing or Random Number Generation not 
receiving cryptographically strong values 
● Developer must explicitly initialize the PRNG 
PRNGFixes.apply() 
Android 
Key Management Droidcon London 2014
Generate Secret Key 
javax.crypto.KeyGenerator 
● Symmetric cryptographic keys generator 
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES","SC"); 
keyGenerator.init(outputKeyLength, secureRandom); 
Specify Key Size 
SecretKey key = keyGenerator.generateKey(); 
Algorithm 
and Provider 
Key to use in Cipher.init() 
Android 
Key Management Droidcon London 2014
Key Management: Store on device 
● Protected by Android Filesystem Isolation 
● Plain File 
● SharedPreferences 
● Keystore File (BKS, JKS) 
● More secure with Phone Encryption 
● Store safely 
● MODE_PRIVATE flag 
● Use only internal storage 
/data/data/app_package 
Android 
Key Management Droidcon London 2014
Key Management: Store on device 
➢ Device rooted? 
○ Check at run-time... 
Android 
Key Management Droidcon London 2014
Key Management: Store in App 
REVERSING 
● Uses static keys or device specific information at run-time 
(IMEI, mac address, ANDROID_ID) 
● Android app can be easily reversed 
● Hide with Code obfuscation Android 
Key Management Droidcon London 2014
Key Management: PBKDF2 
● Password Based Key Derivation Function (PKCS#5) 
● Variable length password in input 
● Fixed length key in output 
● User interaction required 
● Params: 
○ Password 
○ Pseudorandom Function 
○ Salt 
○ Number of iteration 
○ Key Size 
● Available with BC 
Android 
Key Management Droidcon London 2014
Key Management: PBKDF2 
javax.crypto.spec.PBEKeySpec 
● PBE Key specification and generation 
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 
NUM_OF_ITERATIONS, KEY_SIZE); 
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance 
(PBE_ALGORITHM); 
encKey = secretKeyFactory.generateSecret(keySpec); 
A good PBE algorithm is 
PBKDF2WithHmacSHA1 
User 
Password 
N. >= 1000 
Android 
Key Management Droidcon London 2014
SecretKeyFactory API in Android 4.4 
SecretKeyFactory factory; 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) 
// Use compatibility key factory -- only uses lower 8-bits of passphrase chars 
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1And8bit"); 
else if (Build.VERSION.SDK_INT >= 10) 
// Traditional key factory. Will use lower 8-bits of passphrase chars on 
// older Android versions (API level 18 and lower) and all available bits 
// on KitKat and newer (API level 19 and higher) 
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
else // FIX for Android 8,9 
factory = SecretKeyFactory.getInstance("PBEWITHSHAAND128BITAES-CBC-BC"); 
Android 
Key Management Droidcon London 2014
Key Management: Other solutions 
● Store on server side 
● Internet connection required 
● Use trusted and protected connections (HTTPS, Certificate 
Pinning) 
● Store on external device 
● NFC Java Card (NXP J3A081) 
● Smartcard 
● USB PenDrive 
● MicroSD with secure storage 
● AndroidKeyStore??? 
Android 
Key Management Droidcon London 2014
Asymmetric Algorithms 
● Public/Private Key 
○ Public Key -> encrypt/verify signature 
○ Private Key -> decrypt/sign 
● Advantages: 
○ Public Key distribution is not dangerous 
● Disadvantages: 
○ Computationally expensive 
● Usually used with PKI (Public Key Infrastructure for digital 
certificates) 
Android 
Key Management Droidcon London 2014
Public-key Applications 
● Can classify uses into 3 categories: 
○ Encryption/Decryption (provides Confidentiality) 
○ Digital Signatures (provides Authentication and Integrity) 
○ Key Exchange (of Session Keys) 
● Some algorithms are suitable for all uses (RSA), 
others are specific to one 
Android 
Key Management Droidcon London 2014
PKCS for Asymmetric Algorithms 
● PKCS is a group of public-key cryptography 
standards published by RSA Security Inc 
● PKCS#1 (v.2.1) 
○ RSA Cryptography Standard 
● PKCS#3 (v.1.4) 
○ Diffie-Hellman Key Agreement Standard 
● PKCS#8 (v.1.2) 
○ Private-Key Information Syntax Standard 
● PKCS#10 (v.1.7) 
○ Certification Request Standard 
● PKCS#12 (v.1.0) 
○ Personal Information Exchange Syntax Standard 
Android 
Key Management Droidcon London 2014
Android: RSA 
Java.security.KeyPairGenerator 
● KeyPairGenerator is an engine capable of 
generating public/private keys with specified 
algorithms 
KeyPairGenerator kpg = 
KeyPairGenerator.getIstance(”RSA"); 
Cryptographic Algorithm 
Android 
Key Management Droidcon London 2014
Available Providers for RSA Algorithm 
Java.security.KeyPairGenerator 
● Different security providers could be used (could 
change for different OS versions) 
KeyPairGenerator.getInstance(”RSA”,”SEC_PROVIDERS”); 
“AndroidOpenSSL” 
“BC” 
“AndroidKeyStore” 
“GmsCore_OpenSSL” 
Version 1.0 
Version 1.49 
Version 1.0 
Android 
Key Management Droidcon London 2014
KeyPairGenerator: Initialization and 
Randomness 
Java.security.KeyPairGenerator 
● KeyPairGenerator initialization with the key size 
KeyPairGenerator kpg = 
KeyPairGenerator.initialize(2048); 
● KeySize – 1024,2048,4096 bits 
Key Size 
Android 
Key Management Droidcon London 2014
KeyPairGenerator: Initialization and 
Randomness 
Java.security.KeyPairGenerator, Java.security.SecureRandom 
● KeyPairGenerator initialization with a 
SecureRandom 
SecureRandom sr = new SecureRandom(); 
KeyPairGenerator kpg = 
KeyPairGenerator.initialize(2048,sr); 
Android 
Key Management Droidcon London 2014
Generating RSA Key 
Java.security.KeyPair 
● KeyPair is a container for a public/private key 
generated by the KeyPairGenerator 
KeyPair keypair = kpg.genKeyPair() 
● We can retrieve public/private keys from KeyPair 
Key public_key = kaypair.getPublic(); 
Key private_key = kaypair.getPrivate(); 
Android 
Key Management Droidcon London 2014
Using RSA Keys: cipher example 
Javax.crypto.Cipher 
● Cipher provides access to implementation of 
cryptography ciphers for encryption and decryption 
Cipher cipher = Cipher.getInstance(“RSA”,”SEC_PROVIDER); 
Transformation 
“AndroidOpenSSL” 
“BC” 
“AndroidKeyStore” 
“GmsCore_OpenSSL” 
Android 
Key Management Droidcon London 2014
Using RSA Key: cipher example 
Javax.crypto.Cipher 
● Encryption 
cipher.init(Cipher.ENCRYPT_MODE,public_key); 
byte[] encrypted_data= 
cipher.doFinal(“DroidconUK-2014”.getBytes()); 
● Decryption 
cipher.init(Cipher.DECRYPT_MODE,private_key); 
byte[] decrypted_data= 
cipher.doFinal(cipherd_data); 
Android 
Key Management Droidcon London 2014
Parameters of RSA Keys 
java.security.KeyFactory, java.security.spec, 
● Retrieve RSA Key parameters using KeyFactory 
RSAPublicKeySpec rsa_public= keyfactory. 
getKeySpec(keypair.getPublic(), 
RSAPublicKeySpec.class); 
RSAPrivateKeySpec rsa_private = keyfactory.getKeySpec 
(keypair.getPrivate(), 
RSAPrivateKeySpec.class); 
Android 
Key Management Droidcon London 2014
Extract Parameters of RSA Keys 
Java.security.spec.RSAPublicKeySpec, java.security.spec.RSAPrivateKeySpec 
● Retrieved parameters can be stored 
BigInteger m = rsa_public.getModulus(); 
BigInteger e = rsa_public.getPublicExponent(); 
BigInteger d = rsa_private.getPrivateExponent(); 
Is Private 
Android 
Key Management Droidcon London 2014
AndroidKeyStore 
● Custom Java Security Provider available from Android 4.3 
version and beyond 
● An App can generate and save private keys 
● Keys are private for each App 
● 2048-bit key size (4.3), 1024-2048-4096-bit key size (4.4) can 
be stored 
● ECDSA support added from Android 4.4 
Android 
Key Management Droidcon London 2014
Key Management Evolution 
API LEVEL 14 API LEVEL 18 
Global Level: 
KeyChain 
( Public API ) 
App Level: 
KeyStore 
( Closed API ) 
Global Level Only: 
Default TrustStore 
cacerts.bks 
(ROOTED device) 
Global Level: 
KeyChain 
( Public API ) 
App Level and per 
User Level: 
AndroidKeyStore 
( Public API ) 
Android 
Key Management Droidcon London 2014
AndroidKeyStore Storage 
● Two kinds of storage 
○ Hardware-backed (Nexus 7, Nexus 4, 
Nexus 5 :-) with OS >= 4.3) 
○ Secure Element 
○ TPM 
○ TrustZone 
○ Software only (Other devices with OS 
>= 4.3) 
Android 
Key Management Droidcon London 2014
Type of Storage 
import android.security.KeyChain; 
if (KeyChain.isBoundKeyAlgorithm("RSA")) 
// Hardware-Backed 
else 
// Software Only 
Android 
Key Management Droidcon London 2014
Certificate parameters 
Context cx = getActivity(); 
String pkg = cx.getPackageName(); 
Calendar notBefore = Calendar.getInstance(); 
Calendar notAfter = Calendar.getInstance(); 
notAfter.add(1, Calendar.YEAR); 
Time parameters 
import android.security.KeyPairGeneratorSpec.Builder; 
Builder builder = new KeyPairGeneratorSpec.Builder(cx); 
builder.setAlias(“DEVKEY1”); 
String infocert = String.format("CN=%s, OU=%s", “DEVKEY1”, pkg); 
builder.setSubject(new X500Principal(infocert)); 
builder.setSerialNumber(BigInteger.ONE); 
builder.setStartDate(notBefore.getTime()); 
builder.setEndDate(notAfter.getTime()); 
KeyPairGeneratorSpec spec = builder.build(); 
ALIAS to index the 
certificate 
Self-Signed X.509 
● Common Name(CN) 
● Subject(OU) 
● Serial Number 
Generate certificate 
Android 
Key Management Droidcon London 2014
Generating Public/Private keys 
KeyPairGenerator kpGenerator; 
kpGenerator = KeyPairGenerator 
.getInstance("RSA", "AndroidKeyStore"); 
kpGenerator.initialize(spec); 
Init Engine with certificate parameters 
KeyPair kp; 
kp = kpGenerator.generateKeyPair(); 
Engine to generate 
Public/Private key 
Init Engine with: 
● RSA Algorithm 
● Provider: AndroidKeyStore 
● Generating Private/Public key 
After generation, the keys will be stored into AndroidKeyStore and will be 
accessible by ALIAS 
Android 
Key Management Droidcon London 2014
AndroidKeyStore Initialization 
keyStore = KeyStore.getInstance("AndroidKeyStore"); 
keyStore.load(null); 
Get a reference to the AndroidKeyStore 
Should be used if there is an InputStream to load 
(for example the name of imported KeyStore). If not 
used the App will crash 
Now we have the KeyStore reference that will be used to 
access to the Private/Public key by the ALIAS 
Android 
Key Management Droidcon London 2014
RSA Encryption 
● Encryption 
○ Confidentiality 
○ RSA Public key to Encrypt 
○ RSA Private key to Decrypt 
KeyStore.Entry entry = keyStore.getEntry(“DEVKEY1”, null); 
PublicKey publicKeyEnc = ((KeyStore.PrivateKeyEntry) entry) 
.getCertificate().getPublicKey(); 
String textToEncrypt = new String(”DroidconUK-2014"); 
Access to keys identified 
by ALIAS 
Access to Public key to 
Cipher encCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
encCipher.init(Cipher.ENCRYPT_MODE, publicKeyEnc); 
byte[] encryptedText = encCipher.doFinal(byteTextToEncrypt); 
encrypt 
● Algorithm 
● Encryption with 
Public key 
Ciphered 
Android 
Key Management Droidcon London 2014
RSA Decryption 
Cipher decCipher = null; 
byte[] plainTextByte = null; 
decCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
decCipher.init(Cipher.DECRYPT_MODE, 
((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); 
plainTextByte = decCipher.doFinal(byteEcryptedText); 
String plainText = new String(plainTextByte); 
Algorithm 
Decryption with 
Private key 
Plaintext 
Android 
Key Management Droidcon London 2014
RSA Digital Signature 
● Digital Signature 
○ Authentication, Non-Repudiation and Integrity 
○ RSA Private key to Sign 
○ RSA Public Key to Verify 
KeyStore.Entry entry = keyStore.getEntry(“DEVKEY1”, null); 
Access to Private/Public key 
s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); 
s.initVerify(((KeyStore.PrivateKeyEntry) entry).getCertificate()); 
s.update(data); 
boolean valid = s.verify(signature); 
identified by ALIAS 
Private key to sign 
Public Key in 
certificate to verify 
signature 
Android 
Key Management Droidcon London 2014
Issue 61989 … 
Android 
Key Management Droidcon London 2014
KeyChain 
● KeyChain 
○ Accessible by any Application 
● Typically used for corporate certificates 
Android 
Key Management Droidcon London 2014
Example: Import Certificates 
● Import .p12 certificates 
Intent intent = KeyChain.createInstallIntent(); 
byte[] p12 = readFile(“CERTIFICATE_NAME.p12”); 
Intent.putExtra(KeyChain.EXTRA_PKCS12,p12); 
Specify PKCS#12 Key to install 
startActivity(intent); The user will be prompted 
for the password 
Android 
Key Management Droidcon London 2014
Example: Retrieve the key 
● The KeyChainAliasCallback invoked when a user chooses a 
certificate/private key 
KeyChain.choosePrivateKeyAlias( 
Activity activity, 
KeyChainAliasCallBack response, 
String[] keyTypes, 
Principal[] issuers, 
String host, 
Int port, 
String Alias); 
Android 
Key Management Droidcon London 2014
Example: Retrieve and use the keys 
● KeyChainAliasCallbak must implement the abstract method 
alias: 
@Override 
public void alias(String alias){ 
.. 
PrivateKey private_key = KeyChain. 
getPrivateKey(this,alias); 
.. 
Private Key 
X509Certificate[] chain = KeyChain. 
getCertificateChain(this,”DroidconUK-2014”); 
. 
PublicKey public_key = chain[0].getPublicKey(); 
} 
Public Key 
Android 
Key Management Droidcon London 2014
References 
● http://developer.android.com/about/versions/android-4.3.html#Security 
● http://developer.android.com/reference/java/security/KeyStore.html 
● http://en.wikipedia.org/wiki/Encryption 
● http://en.wikipedia.org/wiki/Digital_signature 
● http://nelenkov.blogspot.it/2013/08/credential-storage-enhancements-android-43. 
html 
● http://nelenkov.blogspot.it/2012/05/storing-application-secrets-in-androids.html 
● http://nelenkov.blogspot.it/2012/04/using-password-based-encryption-on.html 
● http://nelenkov.blogspot.it/2011/11/ics-credential-storage-implementation.html 
● http://developer.android.com/reference/android/security/KeyPairGeneratorSpec.html 
● http://android-developers.blogspot.it/2013/02/using-cryptography-to-store-credentials. 
html 
● http://www.bouncycastle.org/ 
● http://android-developers.blogspot.it/2013/08/some-securerandom-thoughts.html 
● http://nelenkov.blogspot.it/2013/10/signing-email-with-nfc-smart-card.html 
● http://en.wikipedia.org/wiki/PKCS 
● http://developer.android.com/reference/android/security/KeyChain.html 
● http://android-developers.blogspot.it/2013/12/changes-to-secretkeyfactory-api-in. 
html 
Android 
Key Management Droidcon London 2014
Thank you 
Q&A 
www.mseclab.com 
www.consulthink.it 
research@mseclab.com 
Android 
Key Management Droidcon London 2014

More Related Content

More from Consulthinkspa

DevOps - Come diventare un buon DevOpper
DevOps -  Come diventare un buon DevOpperDevOps -  Come diventare un buon DevOpper
DevOps - Come diventare un buon DevOpperConsulthinkspa
 
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...Consulthinkspa
 
Scenari introduzione Application Service Governance in Azienda
Scenari introduzione Application Service Governance in AziendaScenari introduzione Application Service Governance in Azienda
Scenari introduzione Application Service Governance in AziendaConsulthinkspa
 
Droidcon it 2015: Android Lollipop for Enterprise
Droidcon it 2015: Android Lollipop for EnterpriseDroidcon it 2015: Android Lollipop for Enterprise
Droidcon it 2015: Android Lollipop for EnterpriseConsulthinkspa
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentConsulthinkspa
 
IPv6 - Breve panoramica tra mito e realtà
IPv6 - Breve panoramica tra mito e realtàIPv6 - Breve panoramica tra mito e realtà
IPv6 - Breve panoramica tra mito e realtàConsulthinkspa
 
Big data - stack tecnologico
Big data -  stack tecnologicoBig data -  stack tecnologico
Big data - stack tecnologicoConsulthinkspa
 
Quality Software Development LifeCycle
Quality Software Development LifeCycleQuality Software Development LifeCycle
Quality Software Development LifeCycleConsulthinkspa
 
Consulthink @ GDG Meets U - L'Aquila2014 - Codelab: Android Security -Il ke...
Consulthink @ GDG Meets U -  L'Aquila2014  - Codelab: Android Security -Il ke...Consulthink @ GDG Meets U -  L'Aquila2014  - Codelab: Android Security -Il ke...
Consulthink @ GDG Meets U - L'Aquila2014 - Codelab: Android Security -Il ke...Consulthinkspa
 
Android Security - Key Management at GDG DevFest Rome 2013
Android Security - Key Management at GDG DevFest Rome 2013 Android Security - Key Management at GDG DevFest Rome 2013
Android Security - Key Management at GDG DevFest Rome 2013 Consulthinkspa
 
Prevenzione degli attacchi informatici che coinvolgono dati sensibili aziendali
Prevenzione degli attacchi informatici che coinvolgono dati sensibili aziendaliPrevenzione degli attacchi informatici che coinvolgono dati sensibili aziendali
Prevenzione degli attacchi informatici che coinvolgono dati sensibili aziendaliConsulthinkspa
 

More from Consulthinkspa (13)

DevOps - Come diventare un buon DevOpper
DevOps -  Come diventare un buon DevOpperDevOps -  Come diventare un buon DevOpper
DevOps - Come diventare un buon DevOpper
 
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
Increasing Android app security for free - Roberto Gassirà, Roberto Piccirill...
 
Consulthink Overview
Consulthink OverviewConsulthink Overview
Consulthink Overview
 
Scenari introduzione Application Service Governance in Azienda
Scenari introduzione Application Service Governance in AziendaScenari introduzione Application Service Governance in Azienda
Scenari introduzione Application Service Governance in Azienda
 
Droidcon it 2015: Android Lollipop for Enterprise
Droidcon it 2015: Android Lollipop for EnterpriseDroidcon it 2015: Android Lollipop for Enterprise
Droidcon it 2015: Android Lollipop for Enterprise
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
IPv6 - Breve panoramica tra mito e realtà
IPv6 - Breve panoramica tra mito e realtàIPv6 - Breve panoramica tra mito e realtà
IPv6 - Breve panoramica tra mito e realtà
 
BitCoin Protocol
BitCoin ProtocolBitCoin Protocol
BitCoin Protocol
 
Big data - stack tecnologico
Big data -  stack tecnologicoBig data -  stack tecnologico
Big data - stack tecnologico
 
Quality Software Development LifeCycle
Quality Software Development LifeCycleQuality Software Development LifeCycle
Quality Software Development LifeCycle
 
Consulthink @ GDG Meets U - L'Aquila2014 - Codelab: Android Security -Il ke...
Consulthink @ GDG Meets U -  L'Aquila2014  - Codelab: Android Security -Il ke...Consulthink @ GDG Meets U -  L'Aquila2014  - Codelab: Android Security -Il ke...
Consulthink @ GDG Meets U - L'Aquila2014 - Codelab: Android Security -Il ke...
 
Android Security - Key Management at GDG DevFest Rome 2013
Android Security - Key Management at GDG DevFest Rome 2013 Android Security - Key Management at GDG DevFest Rome 2013
Android Security - Key Management at GDG DevFest Rome 2013
 
Prevenzione degli attacchi informatici che coinvolgono dati sensibili aziendali
Prevenzione degli attacchi informatici che coinvolgono dati sensibili aziendaliPrevenzione degli attacchi informatici che coinvolgono dati sensibili aziendali
Prevenzione degli attacchi informatici che coinvolgono dati sensibili aziendali
 

Recently uploaded

FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 

Recently uploaded (7)

FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 

Android Key Management @Droidcon London 2014

  • 1. Android Key Management Roberto Piccirillo (r.piccirillo@mseclab.com) Roberto Gassirà (r.gassira@mseclab.com) Droidcon London 2014
  • 2. Roberto Piccirillo ● Senior Security Analyst - Mobile Security Lab ○ Vulnerability Assessment (IT, Mobile Application) ○ Hijacking Mobile Data Connection ■ BlackHat Europe 2009 ■ DeepSec Vienna 2009 ■ HITB Amsterdam 2010 ○ Android Secure Development ● GDG Rome Lab @robpicone Android Key Management Droidcon London 2014
  • 3. Roberto Gassirà ● Senior Security Analyst - Mobile Security Lab ○ Vulnerability Assessment (IT, Mobile Application) ○ Hijacking Mobile Data Connection ■ BlackHat Europe 2009 ■ DeepSec Vienna 2009 ■ HITB Amsterdam 2010 ○ Android Secure Development ● GDG Rome Lab @robgas Android Key Management Droidcon London 2014
  • 4. Android Key Management: Agenda ● Mobile Application Cryptography ● Key Management and CryptoSystem ● Crypto in Android ● Symmetric Encryption ● Symmetric Key Management ● Asymmetric key: Encryption/Digital Signature ● Keychain e AndroidKeyStore Android Key Management Droidcon London 2014
  • 5. Mobile Application Cryptography ➢ Protect Data: ○ Sensitive Data ○ Backup on /sdcard ➢ Exchange data securely: Android Key Management Droidcon London 2014
  • 6. Key Management "Key management is the management of cryptographic keys in a cryptosystem." Android Key Management Droidcon London 2014
  • 7. CryptoSystem "refers to a suite of algorithms needed to implement a particular form of encryption and decryption" ● Two types of encryption: ○ Symmetric Key Algorithms ■ Identical key for encryption/decryption ■ AES, Blowfish, DES, Triple DES ○ Asymmetric Key Algorithms ■ Pair of keys (public/private) for encryption/decryption ■ RSA, DSA, ECDSA Android Key Management Droidcon London 2014
  • 8. Symmetric Key Algorithms: Ciphers ● Two types of ciphers: ○ Block: Process entire blocks of fixed-length groups of bits at a time (padding may be required) ○ Stream: Process single bit at a time(no padding) ● Block Cipher modes of operation: ○ ECB: each block encrypted independently ○ CBC, CFB, OFB: (feedback mode) each block is encrypted combined with the previous encrypted block (starting from an IV) ○ CTR: each block xored with the encrypted successive values of a counter ( starting from a nonce) ECB CBC Android Key Management Droidcon London 2014
  • 9. Crypto in Android ● Framework based on JCA ( Java Cryptography Architecture) ● Provides API for: ● Encryption/Decryption ● Message digests (hashes) ● Key management ● Secure random number generation ● API implemented by Cryptographic Service "Provider" ● "Dynamic" Provider: javax.crypto.* java.security.* Android Key Management Droidcon London 2014
  • 10. Default Providers ➢ From the beginning ○ Bouncy Castle (Customized): ■ Some services and API removed ■ Varies between Android versions ■ Fixed only in the latest versions ○ Crypto (Apache Harmony) ■ Few basic services ■ Only for backward compatibility ➢ From Android 4.0 ○ AndroidOpenSSL: ■ OpenSSL JNI ■ Performance Improved ■ Vulnerable to Heartbleed in 4.1.1 Android Key Management Droidcon London 2014
  • 11. ➢ Spongy Castle (SC) Dynamic Providers ○ Repackage of Bouncy Castle ○ Supports more cryptographic options ○ Not vulnerable to the Heartbleed Bug ○ Up-to-date ➢ GPS Dynamic Security Provider ○ Available from Play Services 5.0 ○ Based on OpenSSL ( No Heartbleed) ○ Rapid delivery of security patches ○ Vendor independent !!! Android Key Management Droidcon London 2014
  • 12. Cipher Benchmarks CBC CTR Run on Google Nexus 5 Android 4.4.4 Android Key Management Droidcon London 2014
  • 13. Cipher Class Secret Key Specification Cipher getInstance Cipher Init Cipher Final Android Key Management Droidcon London 2014
  • 14. SecretKey Specification javax.crypto.spec.SecretKeySpec ● SecretKeySpec specifies a key for a specific algorithm SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Encryption/Decryption Key Cryptographic Algorithm Android Key Management Droidcon London 2014
  • 15. Cipher GetInstance javax.crypto.Cipher ● Create cryptographic cipher Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding”,“SC”); Transformation (describes set of operation to perform): • algorithm/mode/padding • algorithm Provider ( SpongyCastle ) Android Key Management Droidcon London 2014
  • 16. Cipher Init javax.crypto.Cipher ● Initializes the cipher instance with the specified operational mode, key and algorithm parameters. cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv)); Operational Mode: • ENCRYPT_MODE • DECRYPT_MODE • WRAP_MODE • UNWRAP_MODE SecretKeySpec Specify Cipher Algorithm parameters ( IV for CBC ) Android Key Management Droidcon London 2014
  • 17. Cipher Final javax.crypto.Cipher ● Complete a multi-part transformation (encryption or decryption) byte[] encryptedText = cipher.doFinal(clearText.getBytes()); Encrypted Text in byte ClearText in bytes Android Key Management Droidcon London 2014
  • 18. Key Generation: SecureRandom java.security.SecureRandom ● Cryptographically secure pseudo-random number generator SecureRandom secureRandom = new SecureRandom(); Default constructor uses the most cryptographically strong provider available ● Seeding SecureRandom is dangerous: ○ Not Secure ○ Output may change Android Key Management Droidcon London 2014
  • 19. Some SecureRandom Thoughts... http://android-developers.blogspot.it/2013/08/some-securerandom-thoughts.html ● Android security team discovered in August 2013 an improper PRNG initialization for default OpenSSL provider ● Applications invoking system-provided OpenSSL PRNG without explicit initialization are also affected ● Key Generation, Signing or Random Number Generation not receiving cryptographically strong values ● Developer must explicitly initialize the PRNG PRNGFixes.apply() Android Key Management Droidcon London 2014
  • 20. Generate Secret Key javax.crypto.KeyGenerator ● Symmetric cryptographic keys generator KeyGenerator keyGenerator = KeyGenerator.getInstance("AES","SC"); keyGenerator.init(outputKeyLength, secureRandom); Specify Key Size SecretKey key = keyGenerator.generateKey(); Algorithm and Provider Key to use in Cipher.init() Android Key Management Droidcon London 2014
  • 21. Key Management: Store on device ● Protected by Android Filesystem Isolation ● Plain File ● SharedPreferences ● Keystore File (BKS, JKS) ● More secure with Phone Encryption ● Store safely ● MODE_PRIVATE flag ● Use only internal storage /data/data/app_package Android Key Management Droidcon London 2014
  • 22. Key Management: Store on device ➢ Device rooted? ○ Check at run-time... Android Key Management Droidcon London 2014
  • 23. Key Management: Store in App REVERSING ● Uses static keys or device specific information at run-time (IMEI, mac address, ANDROID_ID) ● Android app can be easily reversed ● Hide with Code obfuscation Android Key Management Droidcon London 2014
  • 24. Key Management: PBKDF2 ● Password Based Key Derivation Function (PKCS#5) ● Variable length password in input ● Fixed length key in output ● User interaction required ● Params: ○ Password ○ Pseudorandom Function ○ Salt ○ Number of iteration ○ Key Size ● Available with BC Android Key Management Droidcon London 2014
  • 25. Key Management: PBKDF2 javax.crypto.spec.PBEKeySpec ● PBE Key specification and generation KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, NUM_OF_ITERATIONS, KEY_SIZE); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance (PBE_ALGORITHM); encKey = secretKeyFactory.generateSecret(keySpec); A good PBE algorithm is PBKDF2WithHmacSHA1 User Password N. >= 1000 Android Key Management Droidcon London 2014
  • 26. SecretKeyFactory API in Android 4.4 SecretKeyFactory factory; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) // Use compatibility key factory -- only uses lower 8-bits of passphrase chars factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1And8bit"); else if (Build.VERSION.SDK_INT >= 10) // Traditional key factory. Will use lower 8-bits of passphrase chars on // older Android versions (API level 18 and lower) and all available bits // on KitKat and newer (API level 19 and higher) factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); else // FIX for Android 8,9 factory = SecretKeyFactory.getInstance("PBEWITHSHAAND128BITAES-CBC-BC"); Android Key Management Droidcon London 2014
  • 27. Key Management: Other solutions ● Store on server side ● Internet connection required ● Use trusted and protected connections (HTTPS, Certificate Pinning) ● Store on external device ● NFC Java Card (NXP J3A081) ● Smartcard ● USB PenDrive ● MicroSD with secure storage ● AndroidKeyStore??? Android Key Management Droidcon London 2014
  • 28. Asymmetric Algorithms ● Public/Private Key ○ Public Key -> encrypt/verify signature ○ Private Key -> decrypt/sign ● Advantages: ○ Public Key distribution is not dangerous ● Disadvantages: ○ Computationally expensive ● Usually used with PKI (Public Key Infrastructure for digital certificates) Android Key Management Droidcon London 2014
  • 29. Public-key Applications ● Can classify uses into 3 categories: ○ Encryption/Decryption (provides Confidentiality) ○ Digital Signatures (provides Authentication and Integrity) ○ Key Exchange (of Session Keys) ● Some algorithms are suitable for all uses (RSA), others are specific to one Android Key Management Droidcon London 2014
  • 30. PKCS for Asymmetric Algorithms ● PKCS is a group of public-key cryptography standards published by RSA Security Inc ● PKCS#1 (v.2.1) ○ RSA Cryptography Standard ● PKCS#3 (v.1.4) ○ Diffie-Hellman Key Agreement Standard ● PKCS#8 (v.1.2) ○ Private-Key Information Syntax Standard ● PKCS#10 (v.1.7) ○ Certification Request Standard ● PKCS#12 (v.1.0) ○ Personal Information Exchange Syntax Standard Android Key Management Droidcon London 2014
  • 31. Android: RSA Java.security.KeyPairGenerator ● KeyPairGenerator is an engine capable of generating public/private keys with specified algorithms KeyPairGenerator kpg = KeyPairGenerator.getIstance(”RSA"); Cryptographic Algorithm Android Key Management Droidcon London 2014
  • 32. Available Providers for RSA Algorithm Java.security.KeyPairGenerator ● Different security providers could be used (could change for different OS versions) KeyPairGenerator.getInstance(”RSA”,”SEC_PROVIDERS”); “AndroidOpenSSL” “BC” “AndroidKeyStore” “GmsCore_OpenSSL” Version 1.0 Version 1.49 Version 1.0 Android Key Management Droidcon London 2014
  • 33. KeyPairGenerator: Initialization and Randomness Java.security.KeyPairGenerator ● KeyPairGenerator initialization with the key size KeyPairGenerator kpg = KeyPairGenerator.initialize(2048); ● KeySize – 1024,2048,4096 bits Key Size Android Key Management Droidcon London 2014
  • 34. KeyPairGenerator: Initialization and Randomness Java.security.KeyPairGenerator, Java.security.SecureRandom ● KeyPairGenerator initialization with a SecureRandom SecureRandom sr = new SecureRandom(); KeyPairGenerator kpg = KeyPairGenerator.initialize(2048,sr); Android Key Management Droidcon London 2014
  • 35. Generating RSA Key Java.security.KeyPair ● KeyPair is a container for a public/private key generated by the KeyPairGenerator KeyPair keypair = kpg.genKeyPair() ● We can retrieve public/private keys from KeyPair Key public_key = kaypair.getPublic(); Key private_key = kaypair.getPrivate(); Android Key Management Droidcon London 2014
  • 36. Using RSA Keys: cipher example Javax.crypto.Cipher ● Cipher provides access to implementation of cryptography ciphers for encryption and decryption Cipher cipher = Cipher.getInstance(“RSA”,”SEC_PROVIDER); Transformation “AndroidOpenSSL” “BC” “AndroidKeyStore” “GmsCore_OpenSSL” Android Key Management Droidcon London 2014
  • 37. Using RSA Key: cipher example Javax.crypto.Cipher ● Encryption cipher.init(Cipher.ENCRYPT_MODE,public_key); byte[] encrypted_data= cipher.doFinal(“DroidconUK-2014”.getBytes()); ● Decryption cipher.init(Cipher.DECRYPT_MODE,private_key); byte[] decrypted_data= cipher.doFinal(cipherd_data); Android Key Management Droidcon London 2014
  • 38. Parameters of RSA Keys java.security.KeyFactory, java.security.spec, ● Retrieve RSA Key parameters using KeyFactory RSAPublicKeySpec rsa_public= keyfactory. getKeySpec(keypair.getPublic(), RSAPublicKeySpec.class); RSAPrivateKeySpec rsa_private = keyfactory.getKeySpec (keypair.getPrivate(), RSAPrivateKeySpec.class); Android Key Management Droidcon London 2014
  • 39. Extract Parameters of RSA Keys Java.security.spec.RSAPublicKeySpec, java.security.spec.RSAPrivateKeySpec ● Retrieved parameters can be stored BigInteger m = rsa_public.getModulus(); BigInteger e = rsa_public.getPublicExponent(); BigInteger d = rsa_private.getPrivateExponent(); Is Private Android Key Management Droidcon London 2014
  • 40. AndroidKeyStore ● Custom Java Security Provider available from Android 4.3 version and beyond ● An App can generate and save private keys ● Keys are private for each App ● 2048-bit key size (4.3), 1024-2048-4096-bit key size (4.4) can be stored ● ECDSA support added from Android 4.4 Android Key Management Droidcon London 2014
  • 41. Key Management Evolution API LEVEL 14 API LEVEL 18 Global Level: KeyChain ( Public API ) App Level: KeyStore ( Closed API ) Global Level Only: Default TrustStore cacerts.bks (ROOTED device) Global Level: KeyChain ( Public API ) App Level and per User Level: AndroidKeyStore ( Public API ) Android Key Management Droidcon London 2014
  • 42. AndroidKeyStore Storage ● Two kinds of storage ○ Hardware-backed (Nexus 7, Nexus 4, Nexus 5 :-) with OS >= 4.3) ○ Secure Element ○ TPM ○ TrustZone ○ Software only (Other devices with OS >= 4.3) Android Key Management Droidcon London 2014
  • 43. Type of Storage import android.security.KeyChain; if (KeyChain.isBoundKeyAlgorithm("RSA")) // Hardware-Backed else // Software Only Android Key Management Droidcon London 2014
  • 44. Certificate parameters Context cx = getActivity(); String pkg = cx.getPackageName(); Calendar notBefore = Calendar.getInstance(); Calendar notAfter = Calendar.getInstance(); notAfter.add(1, Calendar.YEAR); Time parameters import android.security.KeyPairGeneratorSpec.Builder; Builder builder = new KeyPairGeneratorSpec.Builder(cx); builder.setAlias(“DEVKEY1”); String infocert = String.format("CN=%s, OU=%s", “DEVKEY1”, pkg); builder.setSubject(new X500Principal(infocert)); builder.setSerialNumber(BigInteger.ONE); builder.setStartDate(notBefore.getTime()); builder.setEndDate(notAfter.getTime()); KeyPairGeneratorSpec spec = builder.build(); ALIAS to index the certificate Self-Signed X.509 ● Common Name(CN) ● Subject(OU) ● Serial Number Generate certificate Android Key Management Droidcon London 2014
  • 45. Generating Public/Private keys KeyPairGenerator kpGenerator; kpGenerator = KeyPairGenerator .getInstance("RSA", "AndroidKeyStore"); kpGenerator.initialize(spec); Init Engine with certificate parameters KeyPair kp; kp = kpGenerator.generateKeyPair(); Engine to generate Public/Private key Init Engine with: ● RSA Algorithm ● Provider: AndroidKeyStore ● Generating Private/Public key After generation, the keys will be stored into AndroidKeyStore and will be accessible by ALIAS Android Key Management Droidcon London 2014
  • 46. AndroidKeyStore Initialization keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); Get a reference to the AndroidKeyStore Should be used if there is an InputStream to load (for example the name of imported KeyStore). If not used the App will crash Now we have the KeyStore reference that will be used to access to the Private/Public key by the ALIAS Android Key Management Droidcon London 2014
  • 47. RSA Encryption ● Encryption ○ Confidentiality ○ RSA Public key to Encrypt ○ RSA Private key to Decrypt KeyStore.Entry entry = keyStore.getEntry(“DEVKEY1”, null); PublicKey publicKeyEnc = ((KeyStore.PrivateKeyEntry) entry) .getCertificate().getPublicKey(); String textToEncrypt = new String(”DroidconUK-2014"); Access to keys identified by ALIAS Access to Public key to Cipher encCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); encCipher.init(Cipher.ENCRYPT_MODE, publicKeyEnc); byte[] encryptedText = encCipher.doFinal(byteTextToEncrypt); encrypt ● Algorithm ● Encryption with Public key Ciphered Android Key Management Droidcon London 2014
  • 48. RSA Decryption Cipher decCipher = null; byte[] plainTextByte = null; decCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); decCipher.init(Cipher.DECRYPT_MODE, ((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); plainTextByte = decCipher.doFinal(byteEcryptedText); String plainText = new String(plainTextByte); Algorithm Decryption with Private key Plaintext Android Key Management Droidcon London 2014
  • 49. RSA Digital Signature ● Digital Signature ○ Authentication, Non-Repudiation and Integrity ○ RSA Private key to Sign ○ RSA Public Key to Verify KeyStore.Entry entry = keyStore.getEntry(“DEVKEY1”, null); Access to Private/Public key s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); s.initVerify(((KeyStore.PrivateKeyEntry) entry).getCertificate()); s.update(data); boolean valid = s.verify(signature); identified by ALIAS Private key to sign Public Key in certificate to verify signature Android Key Management Droidcon London 2014
  • 50. Issue 61989 … Android Key Management Droidcon London 2014
  • 51. KeyChain ● KeyChain ○ Accessible by any Application ● Typically used for corporate certificates Android Key Management Droidcon London 2014
  • 52. Example: Import Certificates ● Import .p12 certificates Intent intent = KeyChain.createInstallIntent(); byte[] p12 = readFile(“CERTIFICATE_NAME.p12”); Intent.putExtra(KeyChain.EXTRA_PKCS12,p12); Specify PKCS#12 Key to install startActivity(intent); The user will be prompted for the password Android Key Management Droidcon London 2014
  • 53. Example: Retrieve the key ● The KeyChainAliasCallback invoked when a user chooses a certificate/private key KeyChain.choosePrivateKeyAlias( Activity activity, KeyChainAliasCallBack response, String[] keyTypes, Principal[] issuers, String host, Int port, String Alias); Android Key Management Droidcon London 2014
  • 54. Example: Retrieve and use the keys ● KeyChainAliasCallbak must implement the abstract method alias: @Override public void alias(String alias){ .. PrivateKey private_key = KeyChain. getPrivateKey(this,alias); .. Private Key X509Certificate[] chain = KeyChain. getCertificateChain(this,”DroidconUK-2014”); . PublicKey public_key = chain[0].getPublicKey(); } Public Key Android Key Management Droidcon London 2014
  • 55. References ● http://developer.android.com/about/versions/android-4.3.html#Security ● http://developer.android.com/reference/java/security/KeyStore.html ● http://en.wikipedia.org/wiki/Encryption ● http://en.wikipedia.org/wiki/Digital_signature ● http://nelenkov.blogspot.it/2013/08/credential-storage-enhancements-android-43. html ● http://nelenkov.blogspot.it/2012/05/storing-application-secrets-in-androids.html ● http://nelenkov.blogspot.it/2012/04/using-password-based-encryption-on.html ● http://nelenkov.blogspot.it/2011/11/ics-credential-storage-implementation.html ● http://developer.android.com/reference/android/security/KeyPairGeneratorSpec.html ● http://android-developers.blogspot.it/2013/02/using-cryptography-to-store-credentials. html ● http://www.bouncycastle.org/ ● http://android-developers.blogspot.it/2013/08/some-securerandom-thoughts.html ● http://nelenkov.blogspot.it/2013/10/signing-email-with-nfc-smart-card.html ● http://en.wikipedia.org/wiki/PKCS ● http://developer.android.com/reference/android/security/KeyChain.html ● http://android-developers.blogspot.it/2013/12/changes-to-secretkeyfactory-api-in. html Android Key Management Droidcon London 2014
  • 56. Thank you Q&A www.mseclab.com www.consulthink.it research@mseclab.com Android Key Management Droidcon London 2014