Compute Shared Secret
This is the final and most important step. Here, both parties will use their own private key and the other party's public key to independently compute the shared secret. If the protocol is successful, they will both arrive at the exact same secret value.
First, let's compute the shared secret from Party A's perspective. Party A uses its private key (a_private_key.pem) and Party B's public key (b_public_key.pem).
Run the following command:
openssl pkeyutl -derive -inkey a_private_key.pem -peerkey b_public_key.pem -out a_shared_secret.bin
pkeyutl: A utility for performing public key operations.
-derive: This action tells the utility to derive a shared secret.
-inkey a_private_key.pem: Specifies Party A's own private key.
-peerkey b_public_key.pem: Specifies the public key of the other party (the "peer").
-out a_shared_secret.bin: Saves the resulting binary secret to a file.
Next, compute the shared secret from Party B's perspective. Party B uses its private key (b_private_key.pem) and Party A's public key (a_public_key.pem).
Run the following command:
openssl pkeyutl -derive -inkey b_private_key.pem -peerkey a_public_key.pem -out b_shared_secret.bin
Now, you have two files, a_shared_secret.bin and b_shared_secret.bin. To verify the success of the key exchange, these two files must be identical. You can use the cmp (compare) command to check this.
cmp a_shared_secret.bin b_shared_secret.bin
If the files are identical, this command will produce no output and exit silently. This silence signifies success!
For a more visual confirmation, you can also compute the cryptographic hash of both files. The hashes must match.
sha256sum *.bin
You should see an output where both files have the exact same SHA256 hash. The actual hash values will vary between runs, but they must be identical for both files:
e3705a4ab5ae5d86f59dfe968f0177b49d5144e2d731dbd8d41b2eda318412ec a_shared_secret.bin
e3705a4ab5ae5d86f59dfe968f0177b49d5144e2d731dbd8d41b2eda318412ec b_shared_secret.bin
(Note: Your hash values will be different from this example, but the important thing is that the hashes for a_shared_secret.bin and b_shared_secret.bin must be identical, proving both parties derived the same shared secret.)
Congratulations, you have successfully performed a Diffie-Hellman key exchange!