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 Eliptic Curve Cryptography(ECC) in Java?

Encrypt and Decrypt Text File using ECC in Java

Condition for Encrypt and Decrypt Text File using ECC in Java

  • Description:
    Elliptic Curve Cryptography (ECC) offers a highly efficient and secure method for encrypting and decrypting files. In ECC, a key pair consisting of a public and private key is generated. The sender encrypts the file using the recipient's public key, ensuring confidentiality during transmission. The recipient, in turn, uses their private key to decrypt the file and access the original content. ECC offers strong cryptographic security with smaller key sizes, which enhances its performance compared to other encryption schemes like RSA.
    While ECC excels in secure key exchange and digital signatures, it is typically not used for direct file encryption due to performance considerations. Instead, ECC often works in tandem with symmetric encryption algorithms like AES in a hybrid encryption system. In this hybrid approach, ECC is used to exchange the symmetric key securely, and then AES is employed for fast encryption and decryption of the file data.
    ECC’s ability to provide robust security with minimal computational overhead makes it ideal for modern applications that demand both high security and efficiency. Its increasing use in mobile devices, IoT, and secure communications is a testament to its ability to offer strong protection without demanding excessive computational resources.
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.PublicKey;
    import java.security.Security;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class ECC_Algorithm_Client extends javax.swing.JFrame {
    private PublicKey publicKey;
    private int result;
    private int result2;
    private File selectedFile;
    private KeyPair keyPair;
    public ECC_Algorithm_Client() {
    initComponents();
    try {
    Security.addProvider(new BouncyCastleProvider());
    this.publicKey = loadServerPublicKey();
    System.out.println("Client ECC Public Key generated successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jButton2 = new javax.swing.JButton();
    jComboBox1 = new javax.swing.JComboBox<>();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jTextField2 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jButton4 = new javax.swing.JButton();
    jButton5 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea2 = new javax.swing.JTextArea();
    jButton6 = new javax.swing.JButton();
    jButton3.setText("Decript");
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    jButton2.setText("Encript");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setText("ECC_ALGORITHM_ENCRYPTION_CLIENT");
    jButton1.setText("Choose File");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });
    jTextField2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jTextField2ActionPerformed(evt);
    }
    });
    jLabel2.setText("File path");
    jButton4.setText("Choose File");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton4ActionPerformed(evt);
    }
    });
    jButton5.setText("ENCRYPT");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton5ActionPerformed(evt);
    }
    });
    jLabel3.setText("File path");
    jTextArea2.setColumns(20);
    jTextArea2.setRows(5);
    jScrollPane2.setViewportView(jTextArea2);
    jButton6.setText("Server Public Key");
    jButton6.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton6ActionPerformed(evt);
    }
    });
    pack();
    }
    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 jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
    String inputFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();
    try {
    encryptFile(inputFilePath, outputFilePath, publicKey);
    JOptionPane.showMessageDialog(this, "File encrypted successfully.");
    } catch (Exception ex) {
    System.out.println(ex.getMessage());
    }
    }
    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
    display();
    }
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
    new ECC_Algorithm_Client().setVisible(true);
    });
    }
    private void encryptFile(String inputFilePath, String outputFilePath, PublicKey publicKey) throws Exception {
    try {
    byte[] plainText = readFile(inputFilePath);
    Cipher cipher = Cipher.getInstance("ECIES", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] encryptedData = cipher.doFinal(plainText);
    try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
    fos.write(encryptedData);
    fos.flush();
    }
    System.out.println("Encryption complete. Encrypted data saved to " + outputFilePath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    private byte[] readFile(String filePath) throws Exception {
    File file = new File(filePath);
    byte[] data = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(data);
    }
    return data;
    }
    private PublicKey loadServerPublicKey() throws Exception {
    File file = new File("/home/soft20/NetBeansProjects/ECC/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("EC", "BC");
    return keyFactory.generatePublic(keySpec);
    }
    private void display() {
    try {
    byte[] publicKeyBytes = loadServerPublicKey().getEncoded();
    String res = Base64.getEncoder().encodeToString(publicKeyBytes);
    jTextArea2.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.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.SecureRandom;
    import java.security.Security;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    public class ECC_Algorithm_Server extends javax.swing.JFrame {

    private int result;
    private KeyPair keyPair;
    private PublicKey publicKey;
    private PrivateKey privateKey;
    private String serverPublicKey = "/home/soft20/NetBeansProjects/ECC/serverPublicKey.key";

    public ECC_Algorithm_Server() {
    initComponents();

    try {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC", "BC");
    keyPairGenerator.initialize(256, new SecureRandom());
    keyPair = keyPairGenerator.generateKeyPair();
    this.publicKey = keyPair.getPublic();
    this.privateKey = keyPair.getPrivate();
    System.out.println("Server ECC Key Pair generated.");
    System.out.println("Server ECC Key Pair generated successfully.");

    savePublicKeyToFile(publicKey, serverPublicKey);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

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

    jButton2.setText("DECRIPT");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("ECC_ ALGORITHM_DECRYPTION_SERVER");

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

    jLabel2.setText("File path");

    jTextField2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jTextField2ActionPerformed(evt);
    }
    });

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

    jLabel3.setText("File Path");

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

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    jButton5.setText("Server Private Key");
    jButton5.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton5ActionPerformed(evt);
    }
    });
    }

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

    private void decryptFile(String encryptFilePath, String outputFilePath, PrivateKey privateKey) throws Exception {
    try {
    byte[] encryptedData = readFile(encryptFilePath);
    Cipher cipher = Cipher.getInstance("ECIES", "BC");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decryptedData = cipher.doFinal(encryptedData);
    try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
    fos.write(decryptedData);
    }
    System.out.println("Decryption complete. Decrypted data saved to " + outputFilePath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    private byte[] readFile(String filePath) throws Exception {
    File file = new File(filePath);
    byte[] data = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(data);
    }
    return data;
    }

    private void savePublicKeyToFile(PublicKey publicKey, String serverPublickey) throws Exception {
    try (FileOutputStream fos = new FileOutputStream(serverPublickey)) {
    fos.write(publicKey.getEncoded());
    System.out.println("Server public key saved to file.");
    }
    }

    private void display() {
    try {
    byte[] publicKeyBytes = privateKey.getEncoded();
    String res = Base64.getEncoder().encodeToString(publicKeyBytes);
    jTextArea1.setText(res);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    }
Step 1
  • To start the encryption process, select the input file path after setting up the ECC encryption GUI.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm1
  • Encrypt and Decrypt data using eliptic-curve-cryptography-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 eliptic-curve-cryptography-algorithm3
Step 3
  • Select the path of the 'Encrypt.txt' file to begin the encryption process.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm4
Step 4
  • The path of the 'Encrypt.txt' file has been selected for encryption.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm5
Step 5
  • The files input.txt and Encrypt.txt are chosen. When the Encrypt button is clicked, encryption is successfully finished.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm6
Step 6
  • To start the decryption process, select the input file path after setting up the ECC decryption GUI
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm7
  • Encrypt and Decrypt data using eliptic-curve-cryptography-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 eliptic-curve-cryptography-algorithm9
Step 8
  • Select the path of the 'decrypt.txt' file to begin the decryption process.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm10
Step 9
  • The path of the 'decrypt.txt' file has been selected for decryption.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm11
Step 10
  • The files encrypt.txt and decrypt.txt are chosen. When the Decrypt button is clicked, decryption is successfully finished.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm12
Step 11
  • Extract the private key from the generated key pair and use it as the ECC secret key.
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm13
  • Encrypt and Decrypt data using eliptic-curve-cryptography-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 eliptic-curve-cryptography-algorithm15
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm16
  • Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm17
  • Saved Server Public Key:
    Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm18