android - java.security.InvalidKeyException when implementing DH protocol -
in android application implement diffie-hellman protocol in order generate common secret between 2 users.
what following: when first user sends friendship request second one, app generates key pair, storing public 1 in remote database , private in local database.
here code first part:
generatekeys(); localdb.insertprivatekey(userid, entityid, privatekey); remotedb.insertfirstpublickey(userid, entityid, publickey);
the generatekeys method following:
private void generatekeys() { try { final keypairgenerator keypairgenerator = keypairgenerator.getinstance("dh"); keypairgenerator.initialize(1024); final keypair keypair = keypairgenerator.generatekeypair(); privatekey = keypair.getprivate(); publickey = keypair.getpublic(); } catch (exception e) { e.printstacktrace(); } }
when second user accepts request, key pair generated, once again storing private key in local db , public in remote. fetches public key of first user remote db, converts publickey , generate common secret.
here code second part:
generatekeys(); localdb.insertprivatekey(userid, entityid, privatekey); remotedb.insertsecondpublickey(entityid, userid, publickey); string stringfirstpubkey = remotedb.fetchfirstkey(entityid, userid); publickey firstpubkey = stringtopublickey(stringfirstpubkey); byte[] commonsecret = generatecommonsecret(firstpubkey);
the stringtopublickey following:
private publickey stringtopublickey(string stringpubk) throws nosuchalgorithmexception, invalidkeyspecexception { byte[] pubk = base64.decodebase64(stringpubk); keyfactory keyfactory = keyfactory.getinstance("dh"); encodedkeyspec keyspec = new x509encodedkeyspec(pubk); return keyfactory.generatepublic(keyspec); }
and generatacommonsecret:
private byte[] generatecommonsecret(publickey firstpubkey) { try { final keyagreement keyagreement = keyagreement.getinstance("dh"); keyagreement.init(privatekey); keyagreement.dophase(firstpubkey, true); byte[] secretkey = adjustkeylenght(keyagreement.generatesecret()); return secretkey; } catch (exception e) { e.printstacktrace(); } return null; }
also when storing keys convert them string following:
string stringpubk = base64.encodebase64string(publickey.getencoded());
when executing following line in generatecommonsecret
keyagreement.dophase(firstpubkey, true);
i exception
java.security.invalidkeyexception: dhpublickey not keyagreement! @ com.android.org.bouncycastle.jcajce.provider.asymmetric.dh.keyagreementspi.enginedophase(keyagreementspi.java:101) @ javax.crypto.keyagreement.dophase(keyagreement.java:383)
can me finding problem? weird if try in single java class, without storing , retrieving keys, works fine.
Comments
Post a Comment