I am working on an android project for school and I am supposed to do a DHKE(Diffie Hellman Key Exchange). Everything works well, the problem is that it takes a lot of time (really a lot) to generate DHParameters. Basically, in my code, this is the part that is the most time (and battery) consuming:

KeyPairGenerator kpgDH = KeyPairGenerator.getInstance("DH");
KeyPair kpDH = kpgDH.generateKeyPair();

As you can see, the key length is only 512 bits, so it's not long, and it still takes at least 30-40 seconds (best case scenario), but it can go up to 400 seconds. And I've tested it on several phones: Samsung galaxy s2 (quad core), samsung galaxy s4 (quad core), samsung galaxy note 10.1 (quad core). Does anybody know an alternative to generate more quickly the p and g for the Diffie Hellman in order to speed-up the process?

  • Crypto.SE does not want questions about programming. I suspect there is an issue with the random number source. – Hendrik Brummermann Feb 8 '14 at 10:49

First, 512 bits is way too small. Parameters that size can be broken in a month by a small computer cluster. Use 2048.

Second, the Diffie-Hellman parameters are public information. Any sensible cryptographic library would include default parameters -- probably from RFC 3526. (Even if your library doesn't include them, you can still use RFC 3526 parameters if you convert them to its input format.) If you insist on generating your own, do it once and hardcode them. You can even do it on your PC if you'd prefer not to wait.

This Stack Overflow question (mostly) demonstrates how to do it (though it uses 1024 bits; as I said, you should use 2048):


Generating the DH key pair itself is basically instantaneous.

Third, writing your own cryptographic protocol to learn is great, but do not use it in real code, with real user data, money and lives at stake. Designing secure cryptography is extremely difficult. Crypto is especially dangerous because something can look good, seem to work, and still be badly insecure. It takes teams of experts years and several tries to get it right. Use TLS.

Not the answer you're looking for? Browse other questions tagged or ask your own question.