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.
(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());