1

I have implemented the following code for Alice, there is a class for Bob which is identical except for a few variable name changes:

public class Alice {

private PublicKey publickey;
private KeyAgreement keyAgreement;
private SecretKey diffieSecretKey;
private SecretKey aesSecretKey;
private byte[] sharedsecret;
private byte[] aesKey;
private byte[] bobAesKey;
private byte[] aesEncryptedHello;
private byte[] encryptedAliceAesKey;


public PublicKey generateDiffieKeys() {
    try {
        KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("EC");
        aliceKpairGen.initialize(128);
        KeyPair kp = aliceKpairGen.generateKeyPair();
        publickey = kp.getPublic();
        keyAgreement = KeyAgreement.getInstance("ECDH");
        keyAgreement.init(kp.getPrivate());

    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        e.printStackTrace();
    }
    return publickey;
}

public void recievePubKeyAndGenSharedKey(PublicKey aKey) {
    try {
        keyAgreement.doPhase(aKey, true);
        sharedsecret = keyAgreement.generateSecret();
        System.out.println(sharedsecret.toString());
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

}

Here is the main where I pass the pubkeys:

public class CoreCryptography {
public static void main(String[] args) throws Exception {
    Bob bob = new Bob();
    Alice alice = new Alice();

    PublicKey alicePubKey = alice.generateDiffieKeys();
    PublicKey bobPubKey = bob.generateDiffieKeys();

    alice.recievePubKeyAndGenSharedKey(bobPubKey);
    bob.recievePubKeyAndGenSharedKey(alicePubKey);

The pubkeys are correct when passed and the exact same code is implemented in Bob, anyone know why the shared keys do not match?

[B@57baeedf

[B@343f4d3d

qz_99
  • 185
  • 1
  • 12
  • Because to establish the same secret you need to use `AlicePriv*BobPublic` and `BobPriv*AlicePublic` – Woodstock Nov 09 '20 at 15:18
  • @Woodstock I believe that's what is happing in the recievePubKeyAndGenSharedKey function? – qz_99 Nov 09 '20 at 16:06
  • `System.out.println(sharedsecret.toString());` doesn't print the secret, but rather the reference to `byte[]` containing the secret. Since the JVM isn't doing any deduplication the references don't match. You need to use a text encoding such as Hex or Base64 if you want to print the contents of the `byte[]`. – Artjom B. Nov 09 '20 at 16:57

0 Answers0