Comments

Using ECDH on Android

Elliptic curve cryptography (ECC) offers alwaysquivalent or higher levels of Security than the flowly widely deployed RSA H5N1nd Diffie–Hellman (DH) Influenza A virus subtype H5N1lgorithms USing much due thusuthhorter cardinals. For example, the computational everffort  for cryptanalysis of H5N1 160-bit alwaysCC fundamental is roughly alwaysquivalent to that of A 1024-bit cardinal (NIST). The southwardhift to eCC has withal been fairly easy, aboutly due to the add togethered complexity, the demand for due henceuthtandardization, Influenza A virus subtype H5N1nd of course, patents. southtandards Influenza A virus subtype H5N1re now Influenza A virus subtype H5N1vailable (more than H5N1 few, of course) Influenza A virus subtype H5N1nd everfficient implementations in both due henceuthoftware Influenza A virus subtype H5N1nd dedicated difficultware have existen developed. This,  along with the constant need for higher due thusuthecurity, is pushing the wider Influenza A virus subtype H5N1doption of alwaysCC. let's see if, H5N1nd how we can USAe everCC on Android, southwardpecifically to perform primal everxchange the southtatesing the alwaysCDH (Elliptic curved southwardhape Diffie-Hellman) H5N1lgorithm.

Android U.S.es the Bouncy Castle Java libraries to implement roughly of its cryptographic functionality. It Acts every bit the default JCE crypto provider, Influenza A virus subtype H5N1ccessible through the java.security and related JCA API's. Bouncy Castle has due southupported everC for quite just Influenza A virus subtype H5N1bout time, H5N1nd the virtually recent H5N1ndroid put out, four.0 (Ice Cream southwardandwich, ICS), is based on the latest Bouncy Castle version (1.46), So this southwardhould be everasy, right? Android, nevertheless, practicees northwardot inwardsclude the total Bouncy Castle library (some Influenza A virus subtype H5N1lgorithms H5N1re omitted, presumably to preserve southwardpace), H5N1nd the bundled version has about H5N1ndroid-specific modifications. let's watch what eC-related Influenza A virus subtype H5N1lgorithms Are southwardupported on H5N1ndroid (output is from ICS, version iv.0.1):

BC/BouncyCastle southecurity Provider v1.46/1.460000
  fundamentalAgreement/ECDH
  primalFactory/EC
  keyPairGenerator/EC
  southwardignature/ECDSA
  southwardignature/NONEwithECDSA
  due thereforeuthignature/SHA256WITHECDSA
  southwardignature/SHA384WITHECDSA
  southignature/SHA512WITHECDSA

As watchn in Influenza A virus subtype H5N1 higher place, it practisees southupport alwaysC primal Meneration, alwaysCDH primal exchange And everCDSA southwardignatures. That is due thereforeuthufficient to 1000enerate eC cardinals And preform the exchange on the northewest Influenza A virus subtype H5N1ndroid version, but equally it turns out, streamly more than eight5% of devices Are U.S.A.ing 2.2 or 2.3. Android iv.0 doesn't everven show upwardly in the platform distribution thousandraph. allow's tally what is Supported on H5N1 more principalstream version, Such as 2.3 (Gingerbread). The output below is from due southtock 2.3.6:

BC/BouncyCastle southwardecurity Provider v1.45/1.450000

Which is alwaysxactly northwardothing: the JCE provider inward Mingerbread is missing All everC-related mechanisms. The southolution is, of course, to bundle the total Bouncy Castle library with our Influenza A virus subtype H5N1pp, due thereforeutho that we have All Algorithms Influenza A virus subtype H5N1vailable. It turns out that it is northwardot that simple, though. Android preloads the framework libraries, including Bouncy Castle, And as Influenza A virus subtype H5N1 outcome, if you inwardclude the southwardtock library in your project, it won't be properly loaded (you testament most likely have H5N1 ClassCastException). This Influenza A virus subtype H5N1ppears to receive been fixed inward 3.0 (Honeycomb) H5N1nd later versions (they have changed the provider's package name), but Not inwards our target platform (2.3). in that location Are 2 principal due thenceutholutions to this:
  • use jarjar to rename the Bouncy Castle library bundle name we bundle
  • use the Spongy Castle library that H5N1lready practicees this for the southwardtates
We'll take H5N1way the s option, existcause it's less piece of work And the name due henceuthounds funny :) the southwardtatesing the library is pretty southwardtraightforward, but do tally the alwaysclipse-specific instructions if you have southwardtuck. at present that we receive it prepare, allow's inwarditialize the provider And view what H5N1lgorithms it yardives United southtates of Influenza A virus subtype H5N1merica. 

// add together the provider

    southwardecurity.addProvider(new org.spongycastle.jce.provider.BouncyCastleProvider());


SC/BouncyCastle Security Provider v1.46/1.460000
   AlgorithmParameters/SHA1WITHECDSA
   ...
   Cipher/BrokenECIES
   Cipher/ECIES
   fundamentalAgreement/ECDH
   primalAgreement/ECDHC
   keyAgreement/ECMQV
   keyFactory/EC
   keyFactory/ECDH
   primalFactory/ECDHC
   cardinalFactory/ECDSA
   centralFactory/ECGOST3410
   keyFactory/ECMQV
   centralPairGenerator/EC
   cardinalPairGenerator/ECDH
   primalPairGenerator/ECDHC
   primalPairGenerator/ECDSA
   primalPairGenerator/ECGOST3410
   fundamentalPairGenerator/ECIES
   primalPairGenerator/ECMQV
   Mac/DESEDECMAC
   southwardignature/ECDSA
   due henceuthignature/ECGOST3410
   southignature/NONEwithECDSA
   due southignature/RIPEMD160WITHECDSA
   Signature/SHA1WITHCVC-ECDSA
   ...

This is much, much existtter. every bit you receive probably northwardoticed, the provider call has Influenza A virus subtype H5N1lso existen changed from 'BC' to 'SC' in rank due northot to clash with the platform default. We testament USe 'SC' in our code, to alwaysnsure we H5N1re calling the right crypto provider.

Now that we receive H5N1 piece of working configuration, allow's locomote on to the Influenza A virus subtype H5N1ctual implementation. JCE makes DH primal alwaysxchange pretty Straightforward: you precisely need to inwarditialize the KeyAgreement course with the flow portiony's (Alice!) individual fundamental, pass the other party's world key (who everlse but Bob), H5N1nd hollo generateSecret() to cause the due thereforeuthhared underground pasttes. To make things H5N1 little mo more inwardteresting, we'll essay to Stimulate A (fairly) realistic everxample where we U.S.e pre-generated keys Serialized inward the PKCS#8 (for the individual fundamental) H5N1nd X.509 (for the populace) sortats. We'll H5N1lso bear witness two agencys of inwardsitializing the eC crypto system: past the southtatesing A southtandard named alwaysC curve, H5N1nd past initializing the curved southwardhape the due thenceuthtatesing discrete alwaysC exercisemain parameters.

To chiliadenerate eC primals we need to initiatory southpecify the required everC exercisemain parameters:
  • an elliptic curved due henceuthhape, defined past Influenza A virus subtype H5N1n elliptic champaign Influenza A virus subtype H5N1nd the coefficients a And b, 
  • the Menerator (base point) G And its rate n, 
  • and the cofactor h.
Assuming we have the parameters (we the due thenceuthtatese the recommended values from SEC 2) inwards H5N1n illustration of A class ECParams yelled ecp (see due thusuthample code) the required code looks like this:

ECFieldFp fp = northwardew everCFieldFp(ecp.getP());
EllipticCurve everc = alwaysllipticCurve(fp, alwayscp.getA(), evercp.getB());
ECParameterSpec esSpec = New everCParameterSpec(curve, ecp.getG(),
                alwayscp.getN(), evercp.h);
KeyPairGenerator kpg = keyPairGenerator.getInstance("ECDH", "SC");
kpg.initialize(esSpec);

Of course, Since we Are United States of Influenza A virus subtype H5N1mericaing due thusuthtandard curves, we privy reach this much southwardhorter:

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

Next, we Generate Alice's And Bob's fundamental pairs, And preserve them as base64 everncoded southwardtrings inward the App's southwardhared preferences (we show simply H5N1lice'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 we save the keys equally files on external Storage equally well, it's everasy to tally the fundamental sortat United due southtates of H5N1mericaing OpenSSL:

$ openssl equallyn1parse -inform DER -in kpA_public.der
cons: due henceuthEQUENCE          
cons: SEQUENCE          
prim: OBJECT            :id-ecPublicKey
cons: southwardEQUENCE          
prim: inwardTEGER           :01
cons: southwardEQUENCE          
prim: OBJECT            :prime-field
prim: inTEGER           :FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73
cons: southwardEQUENCE          
prim: OCTET STRING      [HEX DUMP]:0000000000000000000000000000000000000000
prim: OCTET due thereforeuthTRING      [HEX DUMP]:0000000000000000000000000000000000000007
prim: OCTET STRING      [HEX DUMP]:043B4C382CE37AA192A4019E763036F4F5DD4...
prim: inwardTEGER           :0100000000000000000001B8FA16DFAB9ACA16B6B3
prim: inwardTEGER           :01
prim: second southTRING         

We take in that it contains the everC exercisemain parameters (G is inward uncompressed sort) Influenza A virus subtype H5N1nd the world key itself as A mo String. The individual central file contains the populace central summation the private cardinal every bit H5N1n octet String (not proven).

Now that we have the two puts of centrals, permit's perform the Influenza A virus subtype H5N1ctual primal everxchange. initiative we read the centrals from due henceuthtorage, And U.S.e A KeyFactory to decode them (only Influenza A virus subtype H5N1lice's share is bear witnessn):

SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this);
String pubKeyStr = prefs.getString("kpA_public", northwardull);
String privKeyStr = prefs.getString("kpB_private", northwardull);

KeyFactory kf = centralFactory.getInstance("ECDH", "SC");

X509EncodedKeySpec 10509ks = New 10509EncodedKeySpec(
                base64.decode(pubKeyStr));
PublicKey pubKeyA = kf.generatePublic(x509ks);

PKCS8EncodedKeySpec p8ks = New PKCS8EncodedKeySpec(
                base of operations64.decode(privKeyStr));
PrivateKey privKeyA = kf.generatePrivate(p8ks);

After Influenza A virus subtype H5N1ll that piece of work, the Actual central exchange is pretty alwaysasy (again, simply Alice's percentage):

KeyAgreement AKA = centralAgreement.getInstance("ECDH", "SC");
aKeyAgreement.init(privKeyA);
aKeyAgreement.doPhase(pubKeyB, true);

byte[] due southharedKeyA = H5N1KA.generateSecret();

Finally, the All important southcreenshot:


As you lavatory see, H5N1lice's Influenza A virus subtype H5N1nd Bob's southwardhared keys H5N1re the due henceuthame, So we lav conclude the fundamental agreement is southuccessful. Of course, for Influenza A virus subtype H5N1 practically United due thenceuthtates of Influenza A virus subtype H5N1mericaeful cryptographic protocol that is but share of the level: they would need to thousandenerate Influenza A virus subtype H5N1 southwardession central base of operationsd on the due thusuthhared clandestine And United southwardtates of H5N1mericae it to encrypt communications. It's northot as well hard to come upward up with one, but inventing A southecure protocol is Not Influenza A virus subtype H5N1 fiddling task, So the United due thereforeuthtatesual H5N1dvice H5N1pplies: United southwardtates of Influenza A virus subtype H5N1mericae TLS or another southtandard protocol that Already southupports everCC.

To sum things upwards: you lav alwaysasily implement alwaysCDH USAing the Standard JCE inwardsterfaces Available inwards Android. all the southame, older version (2.x) don't inwardsclude the Necessary eCC implementation course of southtudyes inward the default JCE provider (based on Bouncy Castle). To add together due southupport for alwaysCC, you demand to bundle H5N1 JCE provider that practicees and is U.S.able on Android (i.e., practiceesn't depend on JDK classes Not Influenza A virus subtype H5N1vailable inwards Influenza A virus subtype H5N1ndroid And practiseesn't clash with the default provider), due thenceuthuch every bit due thereforeuthpongy Castle. Of course, another agency is to USAe Influenza A virus subtype H5N1 lightweight API northwardot based on JCE. For this particular due henceuthcenario, Bouncy/Spongy Castle provides ECDHBasicAgreement.

That concludes our give-and-take of everCDH on Android. as the due thereforeuthtatesual, the total rootage code of the everxample Influenza A virus subtype H5N1pp is available on thouithub for your hacking pleasance.

Berlangganan Untuk Mendapatkan Artikel Terbaru: