blowfish_with_diffie.java
53 linesjava
DOWNLOAD
1// Aim: Program to perform Blowfish encryption with Diffie-Hellman key exchange (Blowfish with Diffie-Hellman Key Exchange).
2import javax.crypto.*;
3import javax.crypto.spec.SecretKeySpec;
4import java.util.*;
5import java.math.BigInteger;
6
7public class blowfish_with_diffie {
8    public static void main(String[] args) throws Exception {
9        // Diffie-Hellman Key Exchange
10        Scanner sc = new Scanner(System.in);
11        System.out.print("Enter a prime number (q): ");
12        BigInteger q = sc.nextBigInteger();
13        System.out.print("Enter a primitive root: ");
14        BigInteger a = sc.nextBigInteger();
15        System.out.print("Enter private key for user A: ");
16        BigInteger xA = sc.nextBigInteger();
17        System.out.print("Enter private key for user B: ");
18        BigInteger xB = sc.nextBigInteger();
19        BigInteger yA = a.modPow(xA, q);
20        BigInteger yB = a.modPow(xB, q);
21        BigInteger kA = yB.modPow(xA, q); // Secret key
22        BigInteger kB = yA.modPow(xB, q); // Secret key verification
23
24        if (!kA.equals(kB)) {
25            System.out.println("Error: Keys do not match!");
26            sc.close();
27            return;
28        }
29
30        byte[] keyBytes = Arrays.copyOf(kA.toByteArray(), 16); // Using 16 bytes for Blowfish key
31        SecretKey key = new SecretKeySpec(keyBytes, "Blowfish");
32
33        // Blowfish Encryption and Decryption
34        System.out.print("Enter text: ");
35        sc.nextLine(); // Consume the newline
36        String msg = sc.nextLine();
37        sc.close();
38        System.out.println("Shared Secret Key: " + kA);
39        System.out.println("Blowfish key : " + Base64.getEncoder().encodeToString(keyBytes));
40
41        Cipher cpr = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
42        cpr.init(Cipher.ENCRYPT_MODE, key);
43        byte[] encrypted = cpr.doFinal(msg.getBytes("UTF-8"));
44        String enctext = Base64.getEncoder().encodeToString(encrypted);
45
46        cpr.init(Cipher.DECRYPT_MODE, key);
47        byte[] decrypted = cpr.doFinal(Base64.getDecoder().decode(enctext));
48        String dectext = new String(decrypted, "UTF-8");
49
50        System.out.println("Encrypted: " + enctext);
51        System.out.println("Decrypted: " + dectext);
52    }
53}