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 RSA (Rivest–Shamir–Adleman) Algorithm in Java?

Encrypt and Decrypt Text File using RSA Algorithm in Java

Condition for Encrypt and Decrypt Text File using RSA Algorithm in Java

  • Description:
    RSA (Rivest–Shamir–Adleman) is a widely used asymmetric encryption algorithm that secures data through a pair of keys: a public key for encryption and a private key for decryption. RSA encryption provides robust security, making it a common choice for securing sensitive data during transmission or storage. The algorithm relies on the mathematical principles of large prime numbers and modular exponentiation, ensuring that the decryption process is computationally infeasible without the corresponding private key.
    The KeyPairGenerator class generates the RSA key pair, consisting of a public key for encrypting the file and a private key for decrypting it. The Cipher class, initialized with the RSA algorithm, handles the actual encryption and decryption of the file content. For encryption, the sender uses the recipient's public key, while the recipient decrypts the file using their private key.
    While RSA excels at securing data, it is generally not used for encrypting large files directly due to performance limitations. Instead, RSA is often combined with symmetric encryption algorithms like AES. In this hybrid encryption approach, RSA encrypts a symmetric key, which then encrypts the actual file content. This combination provides both strong security and efficient processing for large files.
    Proper management of keys is crucial for ensuring the integrity and security of encrypted data. Additionally, implementing secure key storage and handling is essential to prevent unauthorized access or key compromise. By combining RSA with modern encryption practices, developers can create a secure framework for protecting files and messages in Java applications.
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.PublicKey;
    import java.security.spec.X509EncodedKeySpec;
    import javax.crypto.Cipher;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;

    public class RSA_Alg_Client extends javax.swing.JFrame {

    private int result;
    private File selectedFile;
    PublicKey publicKey;

    public RSA_Alg_Client(){
    initComponents();
    loadPublicKey();
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("RSA_ALGORITHM_ENCRYPTION");

    jLabel2.setText("File Path");

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

    jLabel3.setText("File Path");

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

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

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

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);

    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(114, 114, 114)
    .addComponent(jLabel1))
    .addGroup(layout.createSequentialGroup()
    .addGap(51, 51, 51)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel2)
    .addComponent(jLabel3))
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jButton1)
    .addGap(106, 106, 106))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jButton2)
    .addGap(104, 104, 104))
    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 474, Short.MAX_VALUE)
    .addComponent(jTextField1)))
    .addGroup(layout.createSequentialGroup()
    .addGap(255, 255, 255)
    .addComponent(jButton3))
    .addGroup(layout.createSequentialGroup()
    .addGap(179, 179, 179)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(18, Short.MAX_VALUE))
    );

    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(23, 23, 23)
    .addComponent(jLabel1)
    .addGap(33, 33, 33)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel2))
    .addGap(18, 18, 18)
    .addComponent(jButton1)
    .addGap(47, 47, 47)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel3))
    .addGap(18, 18, 18)
    .addComponent(jButton2)
    .addGap(18, 18, 18)
    .addComponent(jButton3)
    .addGap(47, 47, 47)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(48, Short.MAX_VALUE))
    );

    pack();
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    String inputFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();
    try {
    encrypt(inputFilePath,outputFilePath,publicKey);
    JOptionPane.showMessageDialog(this, "File encrypted successfully.");
    } catch (Exception ex) {
    System.out.println(ex.getMessage());
    }
    }

    private static void encrypt(String inputFilePath, String outputFilePath, PublicKey publicKey) throws Exception {
    byte[] plainText = readFile(inputFilePath);
    Cipher cipher = Cipher.getInstance("RSA");
    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);
    }

    private void loadPublicKey() {
    try (FileInputStream fis = new FileInputStream("public.key")) {
    byte[] keyBytes = new byte[(int) new File("public.key").length()];
    fis.read(keyBytes);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    this.publicKey = keyFactory.generatePublic(spec);
    } catch (Exception e) {
    System.out.println("Error loading public key: " + e.getMessage());
    }
    }
    }
  • Server.Java:
    package EncyptionDecryption;

    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 javax.crypto.Cipher;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;


    public class RSA_Alg_Server extends javax.swing.JFrame {
    private int result;
    private File selectedFile;
    private PrivateKey privateKey;
    private PublicKey publicKey;

    public RSA_Alg_Server() {
    initComponents();
    try {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    keyPairGen.initialize(2048);
    KeyPair keyPair = keyPairGen.genKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();
    System.out.println("Private Key Generator Successfully..");

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


    @SuppressWarnings("unchecked")
    // //GEN-BEGIN:initComponents
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("RSA_ALGORITHM_DECRYPTION");

    jLabel2.setText("File Path");

    jLabel3.setText("File Path");

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

    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);
    }
    });

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

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(78, 78, 78)
    .addComponent(jLabel1))
    .addGroup(layout.createSequentialGroup()
    .addGap(34, 34, 34)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel3)
    .addComponent(jLabel2))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 363, Short.MAX_VALUE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(0, 0, Short.MAX_VALUE)))))
    .addGap(34, 34, 34))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addGap(0, 0, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jButton1)
    .addGap(145, 145, 145))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jButton2)
    .addComponent(jButton3))
    .addGap(143, 143, 143))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(62, 62, 62))))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(jLabel1)
    .addGap(32, 32, 32)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel3)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(17, 17, 17)
    .addComponent(jButton1)
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel2))
    .addGap(18, 18, 18)
    .addComponent(jButton2)
    .addGap(35, 35, 35)
    .addComponent(jButton3)
    .addGap(18, 18, 18)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(20, Short.MAX_VALUE))
    );

    pack();
    }//
    //GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
    selectedFile = fileChooser.getSelectedFile();
    jTextField1.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField1.setText("No File Selected ");
    }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
    selectedFile = fileChooser.getSelectedFile();
    jTextField2.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField2.setText("No File Selected ");
    }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed

    }//GEN-LAST:event_jTextField2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    String encryptFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();

    try {
    decryptFile(encryptFilePath, outputFilePath, privateKey);

    JOptionPane.showMessageDialog(this, "File decrypted successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }//GEN-LAST:event_jButton3ActionPerformed

    public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(() -> {
    new RSA_Alg_Server().setVisible(true);
    });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables

    private void decryptFile(String encryptFilePath, String outputFilePath, PrivateKey privateKey) {
    try {
    // Read encrypted data from binary file
    byte[] encryptedData = readFile(encryptFilePath);

    // Decrypt data
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] decryptedData = cipher.doFinal(encryptedData);

    // Write decrypted data back to a text file
    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 encryptFilePath)throws Exception {
    File file = new File(encryptFilePath);
    byte[] data = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(data);
    }
    return data;
    }

    private void savePublicKeyToFile(PublicKey publicKey)throws Exception {
    try (FileOutputStream fos = new FileOutputStream("public.key")) {
    fos.write(publicKey.getEncoded());
    System.out.println("Server public key saved to file.");
    }
    }
    }
Step 1
  • To start the encryption process, select the input file path after setting up the RSA encryption GUI.
  • Encrypt and Decrypt data using rsa-algorithm1
  • Encrypt and Decrypt data using rsa-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 rsa-algorithm3
Step 3
  • Select the path of the 'Encrypt.txt' file to begin the encryption process.
  • Encrypt and Decrypt data using rsa-algorithm4
Step 4
  • The path of the 'Encrypt.txt' file has been selected for encryption.
  • Encrypt and Decrypt data using rsa-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 rsa-algorithm6
Step 6
  • To start the decryption process, select the input file path after setting up the RSA decryption GUI
  • Encrypt and Decrypt data using rsa-algorithm7
  • Encrypt and Decrypt data using rsa-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 rsa-algorithm9
Step 8
  • Select the path of the 'decrypt.txt' file to begin the decryption process.
  • Encrypt and Decrypt data using rsa-algorithm10
Step 9
  • The path of the 'decrypt.txt' file has been selected for decryption.
  • Encrypt and Decrypt data using rsa-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 rsa-algorithm12
Step 11
  • Extract the private key from the generated key pair and use it as the RSA secret key.
  • Encrypt and Decrypt data using rsa-algorithm13
  • Encrypt and Decrypt data using rsa-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 rsa-algorithm15
  • Encrypt and Decrypt data using rsa-algorithm16
  • Encrypt and Decrypt data using rsa-algorithm17
  • Public Key File:
    Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm18
  • Private Key File:
    Encrypt and Decrypt data using eliptic-curve-cryptography-algorithm19