Java - Diffie-Hellman Encryption - Wrong Output
Asked Answered
E

1

0

I'm attempting to implement Diffie-Hellman key exchange. I am a little confused with how to use the secret key once generated.

As seen in the output, the 2 secret keys are generated using the same prime & base as normal in the key exchange, and trade public keys when generating the secret keys, however they are not outputting the same value as I expected.

I'm getting very confused with how to implement this encryption method and would be very grateful for some direction. My overall aim for this is to implement an encrypted SMS Android application.

enter image description here
(The screenshot was unable to capture the entire length of a & b's base & prime)

AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
paramGen.init(512); // number of bits
AlgorithmParameters params = paramGen.generateParameters();
DHParameterSpec dhSpec = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class); 

BigInteger p512 = dhSpec.getP();
BigInteger g512 = dhSpec.getG();

//A  
KeyPairGenerator akpg = KeyPairGenerator.getInstance("DiffieHellman");

DHParameterSpec param = new DHParameterSpec(p512, g512);
System.out.println("Prime: " + p512);
System.out.println("Base: " + g512);
akpg.initialize(param);
KeyPair kp = akpg.generateKeyPair();

//B
KeyPairGenerator bkpg = KeyPairGenerator.getInstance("DiffieHellman");

DHParameterSpec param2 = new DHParameterSpec(p512, g512);
System.out.println("Prime: " + p512);
System.out.println("Base: " + g512);
bkpg.initialize(param2);
KeyPair kp2 = bkpg.generateKeyPair();


KeyAgreement aKeyAgree = KeyAgreement.getInstance("DiffieHellman");
KeyAgreement bKeyAgree = KeyAgreement.getInstance("DiffieHellman");

aKeyAgree.init(kp.getPrivate());
bKeyAgree.init(kp2.getPrivate());

aKeyAgree.doPhase(kp2.getPublic(), true);
bKeyAgree.doPhase(kp.getPublic(), true);

//System.out.println("Alice Secret Key: " + aKeyAgree.generateSecret());
//System.out.println("Bob's Secret Key: " + bKeyAgree.generateSecret());

MessageDigest hash = MessageDigest.getInstance("SHA-256");

byte[] ASharedSecret = hash.digest(aKeyAgree.generateSecret());
byte[] BSharedSecret = hash.digest(bKeyAgree.generateSecret());

System.out.println("Alice's Shared Secret: " + ASharedSecret.toString());
System.out.println("Bob's Shared Secret: " + BSharedSecret.toString());
Erastian answered 18/3, 2014 at 22:30 Comment(2)
You may first wish to check out the information linked to in the answer on your related question. It may be more trouble than it's worth to try and diagnose problems in a low quality example.Saez
I attempted the implementation example, but it only generates the base, prime & exponentErastian
P
2

byte[].toString() doesn't print the contents. Try Arrays.toString().

Personification answered 18/3, 2014 at 23:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.