List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Encrypt and Decrypt the Text File using Diffie-Hellman Key Exchange Algorithm in Java?

Encrypt and Decrypt Text File using Diffie-Hellman Key Exchange Algorithm in Java

Condition for Encrypt and Decrypt Text File using Diffie-Hellman Key Exchange Algorithm in Java

  • Description:
    To establish a shared secret securely over an unsecured channel, Diffie-Hellman (DH) key exchange allows two parties to generate a common secret key. The algorithm involves generating a large prime number and a generator, which both parties use to create their public keys. Each party computes a private key and exchanges public keys, enabling both to derive the same shared secret without directly transmitting it. In Java, the KeyPairGenerator class helps generate the DH key pair, while the KeyAgreement class performs the key exchange. Once the shared secret key is derived, use it with symmetric encryption algorithms like AES to encrypt and decrypt files.
    File encryption requires initializing the Cipher class in ENCRYPT_MODE or DECRYPT_MODE. Use CipherOutputStream and CipherInputStream to securely write or read encrypted file data. Proper exception handling for InvalidKeyException and NoSuchAlgorithmException ensures error-free execution. Closing file streams correctly maintains data integrity and prevents resource leaks.
Sample Code
  • Client.java:
    package Asymmetric;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Arrays;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.CipherOutputStream;
    import javax.crypto.KeyAgreement;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    public class Diffie_Hellman_Client extends javax.swing.JFrame {
    private KeyAgreement keyAgreement;
    private int result;
    private byte[] sharedSecret;
    private PublicKey serverPublicKey;
    private PublicKey publicKey;
    private KeyPair keyPair;
    private SecretKeySpec aesKeySpec;
    public Diffie_Hellman_Client() {
    initComponents();
    try {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
    keyGen.initialize(2048);
    KeyPair keyPair = keyGen.generateKeyPair();
    this.publicKey = keyPair.getPublic();
    savePublicKey(publicKey, "clientPublicKey.key");
    keyAgreement = KeyAgreement.getInstance("DH");
    keyAgreement.init(keyPair.getPrivate());
    this.serverPublicKey = loadServerPublicKey();
    keyAgreement.doPhase(serverPublicKey, true);
    sharedSecret = keyAgreement.generateSecret();
    byte[] aesKey = Arrays.copyOf(sharedSecret, 16);
    aesKeySpec = new SecretKeySpec(aesKey, "AES");
    System.out.println("Shared secret generated successfully on client.");
    } catch (Exception e) {
    System.out.println("Error in client initialization: " + e.getMessage());
    }
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {
    // UI Components Initialization
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField1.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField1.setText("No File Selected ");
    }
    }
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    String inputFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();
    try {
    encryptFile(aesKeySpec, inputFilePath, outputFilePath);
    JOptionPane.showMessageDialog(this, "File encrypted successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    private void encryptFile(SecretKeySpec aesKeySpec, String inputFilePath, String outputFilePath) throws Exception {
    try {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] iv = new byte[16];
    new SecureRandom().nextBytes(iv);
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, aesKeySpec, ivSpec);
    FileInputStream fis = new FileInputStream(inputFilePath);
    try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
    fos.write(iv); // Write IV first
    try (CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
    cos.write(buffer, 0, bytesRead);
    }
    }
    }
    System.out.println("File encrypted successfully: " + outputFilePath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    JOptionPane.showMessageDialog(this, "Error during encryption: " + e.getMessage());
    }
    }
    private PublicKey loadServerPublicKey() throws Exception {
    File file = new File("serverPublicKey.key");
    byte[] keyBytes = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(keyBytes);
    }
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DH");
    return keyFactory.generatePublic(keySpec);
    }
    private void display() {
    try {
    byte[] publicKeyBytes = loadServerPublicKey().getEncoded();
    String res = Base64.getEncoder().encodeToString(publicKeyBytes);
    jTextArea1.setText(res);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
  • Server.Java:
    package Asymmetric;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.nio.file.Files;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Arrays;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.CipherInputStream;
    import javax.crypto.KeyAgreement;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;

    public class Diffie_Hellman_Server extends javax.swing.JFrame {

    private int result;
    private KeyAgreement keyAgreement;
    private byte[] sharedSecret;
    private PublicKey clientPublicKey;
    private PublicKey publicKey;
    private KeyPair keyPair;
    private PrivateKey privateKey;

    public Diffie_Hellman_Server() {
    initComponents();
    try {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
    keyPairGen.initialize(2048);
    keyPair = keyPairGen.generateKeyPair();
    publicKey = keyPair.getPublic();
    savePublicKey(publicKey, "serverPublicKey.key");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jTextField2 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jButton4 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setText("Diffie_Hellman_Decryption");

    jButton1.setText("Choose File");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    jButton2.setText("Choose File");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });

    jButton3.setText("DECRYPT");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    }
    });

    jButton4.setText("Server Public Key");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton4ActionPerformed(evt);
    }
    });

    pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField1.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField1.setText("No File Selected ");
    }
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField2.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField2.setText("No File Selected ");
    }
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    String inputFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();
    try {
    PublicKey clientPublicKey = loadClientPublicKey();
    keyAgreement = KeyAgreement.getInstance("DH");
    keyAgreement.init(keyPair.getPrivate());
    keyAgreement.doPhase(clientPublicKey, true);
    sharedSecret = keyAgreement.generateSecret();
    byte[] aesKey = Arrays.copyOf(sharedSecret, 16);
    SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey, "AES");
    decryptFile(aesKeySpec, new File(inputFilePath), new File(outputFilePath));
    JOptionPane.showMessageDialog(this, "File decrypted successfully.");
    } catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Decryption failed: " + e.getMessage());
    }
    }

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    display();
    }

    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
    new Diffie_Hellman_Server().setVisible(true);
    });
    }

    private static void decryptFile(SecretKeySpec aesKeySpec, File inputFile, File outputFile) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    try (FileInputStream fis = new FileInputStream(inputFile)) {
    byte[] iv = new byte[16];
    fis.read(iv);
    IvParameterSpec ivSpec = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, aesKeySpec, ivSpec);
    try (CipherInputStream cis = new CipherInputStream(fis, cipher); FileOutputStream fos = new FileOutputStream(outputFile)) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = cis.read(buffer)) != -1) {
    fos.write(buffer, 0, bytesRead);
    }
    }
    }
    }

    private void savePublicKey(PublicKey publicKey, String serverPublickey) throws Exception {
    try (FileOutputStream fos = new FileOutputStream(serverPublickey)) {
    fos.write(publicKey.getEncoded());
    }
    }

    private PublicKey loadClientPublicKey() throws Exception {
    File file = new File("clientPublicKey.key");
    byte[] keyBytes = Files.readAllBytes(file.toPath());
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DH");
    return keyFactory.generatePublic(keySpec);
    }

    private void display() {
    try {
    byte[] publicKeyBytes = loadClientPublicKey().getEncoded();
    jTextArea1.setText(Base64.getEncoder().encodeToString(publicKeyBytes));
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    }
Step 1
  • To start the encryption process, select the input file path after setting up the Diffie-Hellman encryption GUI.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm1
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm2
Step 2
  • The chosen file location is indicated by the selected file path that shows up in the text field.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm3
Step 3
  • Select the path of the 'DhEncrypt.txt' file to begin the encryption process.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm4
Step 4
  • The path of the 'DhEncrypt.txt' file has been selected for encryption.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm5
Step 5
  • The files Original.txt and DhEncrypt.txt are chosen. When the Encrypt button is clicked, encryption is successfully finished.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm6
Step 6
  • To start the decryption process, select the input file path after setting up the Diffie-Hellman decryption GUI.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm7
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm8
Step 7
  • The chosen file location is indicated by the selected file path that shows up in the text field.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm9
Step 8
  • Select the path of the 'DhDecrypt.txt' file to begin the decryption process.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm10
Step 9
  • The path of the 'DhDecrypt.txt' file has been selected for decryption.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm11
Step 10
  • The files DhEncrypt.txt and DhDecrypt.txt are chosen. When the Decrypt button is clicked, decryption is successfully finished.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm12
Step 11
  • To use Diffie-Hellman keys, both parties exchange public keys and independently compute the shared secret key using their private keys. This shared secret can then be used for symmetric encryption, such as AES, to securely encrypt and decrypt data.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm13
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm14
Step 12
  • Encryption applies to the input text file, with the result saved in the encrypt text file. Decryption restores the original content from the decrypt text file.
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm15
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm16
  • Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm17
  • Client Public Key:
    Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm18
  • Server Public Key:
    Encrypt and Decrypt data using diffie-hellman-key-exchange-algorithm19