Droidcedas : Using Ecdh On Android

Elliptic crimp cryptography (ECC) offers equivalent or higher levels of safety than the currently widely deployed RSA as well as Diffie–Hellman (DH) algorithms using much shorter keys. For example, the computational effort  for cryptanalysis of a 160-bit ECC fundamental is roughly equivalent to that of a 1024-bit fundamental (NIST). The shift to ECC has silent been fairly slow, to a greater extent than oftentimes than non due to the added complexity, the demand for standardization, as well as of course, patents. Standards are straightaway available (more than a few, of course) as well as efficient implementations inwards both software as well as dedicated hardware receive got been developed. This,  along alongside the constant demand for higher security, is pushing the wider adoption of ECC. Let's come across if, as well as how nosotros tin job ECC on Android, specifically to perform fundamental telephone substitution using the ECDH (Elliptic Curve Diffie-Hellman) algorithm.

Android uses the Bouncy Castle Java libraries to implement around of its cryptographic functionality. It acts equally the default JCE crypto provider, accessible through the java.security and related JCA API's. Bouncy Castle has supported EC for quite around time, as well as the almost recent Android release, 4.0 (Ice Cream Sandwich, ICS), is based on the latest Bouncy Castle version (1.46), as well as thus this should last easy, right? Android, however, does non include the total Bouncy Castle library (some algorithms are omitted, presumably to salvage space), as well as the bundled version has around Android-specific modifications. Let's come across what EC-related algorithms are supported on Android (output is from ICS, version 4.0.1):

BC/BouncyCastle Security Provider v1.46/1.460000   KeyAgreement/ECDH   KeyFactory/EC   KeyPairGenerator/EC   Signature/ECDSA   Signature/NONEwithECDSA   Signature/SHA256WITHECDSA   Signature/SHA384WITHECDSA   Signature/SHA512WITHECDSA 

As seen above, it does back upwards EC fundamental generation, ECDH fundamental telephone substitution as well as ECDSA signatures. That is sufficient to generate EC keys as well as preform the telephone substitution on the newest Android version, but equally it turns out, currently to a greater extent than than 85% of devices are using 2.2 or 2.3. Android 4.0 doesn't fifty-fifty demo upwards inwards the platform distribution graph. Let's cheque what is supported on a to a greater extent than mainstream version, such equally 2.3 (Gingerbread). The output below is from stock 2.3.6:

BC/BouncyCastle Security Provider v1.45/1.450000 

Which is just nothing: the JCE provider inwards Gingerbread is missing all EC-related mechanisms. The solution is, of course, to bundle the total Bouncy Castle library alongside our app, as well as thus that nosotros receive got all algorithms available. It turns out that it is non that simple, though. Android preloads the framework libraries, including Bouncy Castle, as well as equally a result, if you lot include the stock library inwards your project, it won't last properly loaded (you volition almost probable instruct a ClassCastException). This appears to receive got been fixed inwards 3.0 (Honeycomb) as well as after versions (they receive got changed the provider's packet name), but non inwards our target platform (2.3). There are ii master copy solutions to this:
  • use jarjar to rename the Bouncy Castle library packet mention nosotros bundle
  • use the Spongy Castle library that already does this for us
We'll receive got the 2nd option, because it's less piece of work as well as the mention sounds funny :) Using the library is pretty straightforward, but practise cheque the Eclipse-specific instructions if you lot instruct stuck. Now that nosotros receive got it laid up, let's initialize the provider as well as come across what algorithms it gives us. 

// add together the provider {     Security.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()); }  SC/BouncyCastle Security Provider v1.46/1.460000    AlgorithmParameters/SHA1WITHECDSA    ...    Cipher/BrokenECIES    Cipher/ECIES    KeyAgreement/ECDH    KeyAgreement/ECDHC    KeyAgreement/ECMQV    KeyFactory/EC    KeyFactory/ECDH    KeyFactory/ECDHC    KeyFactory/ECDSA    KeyFactory/ECGOST3410    KeyFactory/ECMQV    KeyPairGenerator/EC    KeyPairGenerator/ECDH    KeyPairGenerator/ECDHC    KeyPairGenerator/ECDSA    KeyPairGenerator/ECGOST3410    KeyPairGenerator/ECIES    KeyPairGenerator/ECMQV    Mac/DESEDECMAC    Signature/ECDSA    Signature/ECGOST3410    Signature/NONEwithECDSA    Signature/RIPEMD160WITHECDSA    Signature/SHA1WITHCVC-ECDSA    ... 

This is much, much better. As you lot receive got in all likelihood noticed, the provider mention has also been changed from 'BC' to 'SC' inwards social club non to clash alongside the platform default. We volition job 'SC' inwards our code, to ensure nosotros are calling the right crypto provider.

Now that nosotros receive got a working configuration, let's motion on to the actual implementation. JCE makes DH fundamental telephone substitution pretty straightforward: you lot simply demand to initialize the KeyAgreement flat alongside the electrical current party's (Alice!) soul key, transcend the other party's populace fundamental (who else but Bob), as well as telephone telephone generateSecret() to instruct the shared surreptitious bytes. To brand things a piddling flake to a greater extent than interesting, we'll assay to cause a (fairly) realistic illustration where nosotros job pre-generated keys serialized inwards the PKCS#8 (for the soul key) as well as X.509 (for the public) formats. We'll also demo ii ways of initializing the EC crypto system: past times using a touchstone named EC curve, as well as past times initializing the crimp using discrete EC domain parameters.

To generate EC keys nosotros demand to starting fourth dimension specify the required EC domain parameters:
  • an elliptic curve, defined past times an elliptic champaign as well as the coefficients a as well as b, 
  • the generator (base point) G as well as its social club n, 
  • and the cofactor h.
Assuming nosotros receive got the parameters (we job the recommended values from SEC 2) inwards an illustration of a flat ECParams called ecp (see sample code) the required code looks similar this:

ECFieldFp fp = novel ECFieldFp(ecp.getP()); EllipticCurve ec = EllipticCurve(fp, ecp.getA(), ecp.getB()); ECParameterSpec esSpec = novel ECParameterSpec(curve, ecp.getG(),                 ecp.getN(), ecp.h); KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", "SC"); kpg.initialize(esSpec); 

Of course, since nosotros are using touchstone curves, nosotros tin brand this much shorter:

ECGenParameterSpec ecParamSpec = novel ECGenParameterSpec("secp224k1"); KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDH", "SC"); kpg.initialize(ecParamSpec); 

Next, nosotros generate Alice's as well as Bob's fundamental pairs, as well as salvage them equally Base64 encoded strings inwards the app's shared preferences (we demo alone Alice's part, Bob's is identical):

KeyPair kpA = kpg.generateKeyPair();  String pubStr = Crypto.base64Encode(kpA.getPublic().getEncoded()); String privStr = Crypto.base64Encode(kpA.getPrivate().getEncoded());  SharedPreferences.Editor prefsEditor = PreferenceManager                 .getDefaultSharedPreferences(this).edit();  prefsEditor.putString("kpA_public", pubStr); prefsEditor.putString("kpA_private", privStr); prefsEditor.commit(); 

If nosotros salvage the keys equally files on external storage equally well, it's piece of cake to cheque the fundamental format using OpenSSL:

$ openssl asn1parse -inform DER -in kpA_public.der cons: SEQUENCE           cons: SEQUENCE           prim: OBJECT            :id-ecPublicKey cons: SEQUENCE           prim: INTEGER           :01 cons: SEQUENCE           prim: OBJECT            :prime-field prim: INTEGER           :FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73 cons: SEQUENCE           prim: OCTET STRING      [HEX DUMP]:0000000000000000000000000000000000000000 prim: OCTET STRING      [HEX DUMP]:0000000000000000000000000000000000000007 prim: OCTET STRING      [HEX DUMP]:043B4C382CE37AA192A4019E763036F4F5DD4... prim: INTEGER           :0100000000000000000001B8FA16DFAB9ACA16B6B3 prim: INTEGER           :01 prim: BIT STRING          

We come across that it contains the EC domain parameters (G is inwards uncompressed form) as well as the populace fundamental itself equally a flake string. The soul fundamental file contains the populace fundamental addition the soul fundamental equally an octet string (not shown).

Now that nosotros receive got the ii sets of keys, let's perform the actual fundamental exchange. First nosotros read the keys from storage, as well as job a KeyFactory to decode them (only Alice's portion is shown):

SharedPreferences prefs = PreferenceManager                 .getDefaultSharedPreferences(this); String pubKeyStr = prefs.getString("kpA_public", null); String privKeyStr = prefs.getString("kpB_private", null);  KeyFactory kf = KeyFactory.getInstance("ECDH", "SC");  X509EncodedKeySpec x509ks = novel X509EncodedKeySpec(                 Base64.decode(pubKeyStr)); PublicKey pubKeyA = kf.generatePublic(x509ks);  PKCS8EncodedKeySpec p8ks = novel PKCS8EncodedKeySpec(                 Base64.decode(privKeyStr)); PrivateKey privKeyA = kf.generatePrivate(p8ks); 

After all that work, the actual fundamental telephone substitution is pretty piece of cake (again, alone Alice's part):

KeyAgreement aKA = KeyAgreement.getInstance("ECDH", "SC"); aKeyAgreement.init(privKeyA); aKeyAgreement.doPhase(pubKeyB, true);  byte[] sharedKeyA = aKA.generateSecret(); 

Finally, the all of import screenshot:


As you lot tin see, Alice's as well as Bob's shared keys are the same, as well as thus nosotros tin conclude the fundamental understanding is successful. Of course, for a practically useful cryptographic protocol that is alone portion of the story: they would demand to generate a session fundamental based on the shared surreptitious as well as job it to encrypt communications. It's non equally good difficult to come upwards up alongside one, but inventing a secure protocol is non a trivial task, as well as thus the park advice applies: job TLS or around other touchstone protocol that already supports ECC.

To amount things up: you lot tin easily implement ECDH using the touchstone JCE interfaces available inwards Android. However, older version (2.x) don't include the necessary ECC implementation classes inwards the default JCE provider (based on Bouncy Castle). To add together back upwards for ECC, you lot demand to bundle a JCE provider that does and is usable on Android (i.e., doesn't depend on JDK classes non available inwards Android as well as doesn't clash alongside the default provider), such equally Spongy Castle. Of course, around other means is to job a lightweight API non based on JCE. For this especial scenario, Bouncy/Spongy Castle provides ECDHBasicAgreement.

That concludes our intelligence of ECDH on Android. As usual, the total origin code of the illustration app is available on Github for your hacking pleasure.
0 Komentar untuk "Droidcedas : Using Ecdh On Android"

Back To Top