mail@pastecode.io avatar
7 months ago
2.4 kB
import java.security.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.*;
import java.util.Base64;

public class ECDHDemo {

    public static void main(String[] args) throws Exception {
        // Alice generates her key pair
        KeyPair aliceKeyPair = generateKeyPair();

        // Bob generates his key pair
        KeyPair bobKeyPair = generateKeyPair();

        // Alice and Bob exchange their public keys
        byte[] alicePublicKeyBytes = aliceKeyPair.getPublic().getEncoded();
        byte[] bobPublicKeyBytes = bobKeyPair.getPublic().getEncoded();

        // Alice calculates the secret key using her private key and Bob's public key
        SecretKey aliceSecretKey = deriveSecretKey(aliceKeyPair.getPrivate(), bobPublicKeyBytes);

        // Bob calculates the secret key using his private key and Alice's public key
        SecretKey bobSecretKey = deriveSecretKey(bobKeyPair.getPrivate(), alicePublicKeyBytes);

        // Print the secret keys
        System.out.println("Alice's Secret Key: " + Base64.getEncoder().encodeToString(aliceSecretKey.getEncoded()));
        System.out.println("Bob's Secret Key: " + Base64.getEncoder().encodeToString(bobSecretKey.getEncoded()));

    private static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
        return keyPairGenerator.generateKeyPair();

    private static SecretKey deriveSecretKey(PrivateKey privateKey, byte[] publicKeyBytes) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("EC");
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        KeyAgreement keyAgreement = KeyAgreement.getInstance("ECDH");
        keyAgreement.doPhase(publicKey, true);

        // Generate the shared secret
        byte[] sharedSecret = keyAgreement.generateSecret();

        // Derive a secret key from the shared secret using a key derivation function (KDF)
        SecretKeySpec secretKey = new SecretKeySpec(sharedSecret, "AES");

        return secretKey;
Leave a Comment