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

Office Address

Social List

How to Implement SHA3-256 Hash-Based Key with AES Encryption and Decryption of a Text File using Java?

Encrypt and Decrypt Text File using SHA3-256 Hash-Based Key with AES in Java

Condition for Encrypt and Decrypt Text File using SHA3-256 Hash-Based Key with AES in Java

  • Description:
    To encrypt and decrypt a text file using a SHA3-256 hash-based key with AES in Java, To enhance data security, combine SHA3-256 and AES for secure file encryption and decryption. SHA3-256, a cryptographic hash function from the SHA-3 family, generates a fixed 256-bit hash from input data, ensuring resistance against collision and pre-image attacks. It produces a unique hash value that can serve as a robust key derivation method when combined with AES, a widely used symmetric encryption algorithm known for its speed and security.

    Derive the AES encryption key by hashing a password or passphrase with SHA3-256, ensuring a consistent and secure 256-bit key. Use the MessageDigest class in Java with the "SHA3-256" algorithm to generate the hash.

    Pass the resulting hash as the AES key to the SecretKeySpec class for key specification. The Cipher class, initialized with the "AES" algorithm and either ENCRYPT_MODE or DECRYPT_MODE, handles the encryption or decryption process.

    To encrypt a text file, read its contents as bytes, apply AES encryption using the derived key, and write the encrypted data to an output file. For decryption, reverse the process by using the same SHA3-256-derived key to decrypt the file and restore the original content. Use secure padding schemes like PKCS5Padding to align the data with the block size.

    Ensure secure management of the passphrase and handle exceptions such as InvalidKeyException and NoSuchAlgorithmException effectively. Closing file streams properly prevents resource leaks and maintains data integrity. This hybrid approach combines the strength of SHA3-256 for key derivation and AES for efficient encryption, providing a robust solution for securing sensitive data in Java applications.
Sample Code
  • Encryption:
    package hashFunction;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.security.MessageDigest;
    import java.security.Security;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    public class SHA3_256_Encryption extends javax.swing.JFrame {

    private int result;
    SecretKey secretKey;
    private String keyPath = "/home/soft20/NetBeansProjects/SHA3-256/clientKey.key";

    public SHA3_256_Encryption() {
    initComponents();

    try {
    Security.addProvider(new BouncyCastleProvider());
    String password = "myStrongPassword";
    secretKey = generateKeyFromSHA3_256(password);

    saveKeyToFile(secretKey, keyPath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    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("SHA3-256_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);

    jButton4.setText("SecretKey");
    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();
    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 jButton2ActionPerformed(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();
    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 {
    encrypt(inputFilePath, outputFilePath, secretKey);
    JOptionPane.showMessageDialog(this, "File encrypted successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    private void encrypt(String inputFilePath, String outputFilePath, SecretKey secretKey) {
    try {
    byte[] plainText = readFile(inputFilePath);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] encryptedData = cipher.doFinal(plainText);

    try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
    fos.write(encryptedData);
    fos.flush();
    }
    System.out.println("Encryption successful. Encrypted text saved to: " + outputFilePath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    private byte[] readFile(String inputFilePath) throws Exception {
    File file = new File(inputFilePath);
    byte[] data = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(data);
    }
    return data;
    }
    }
    private SecretKey generateKeyFromSHA3_256(String password) throws Exception {
    MessageDigest sha = MessageDigest.getInstance("SHA3-256", "BC");
    byte[] keyBytes = sha.digest(password.getBytes());
    return new SecretKeySpec(keyBytes, 0, 16, "AES");
    }

    private void saveKeyToFile(SecretKey secretKey, String keyPath) throws Exception {
    byte[] encodedKey = Base64.getEncoder().encode(secretKey.getEncoded());
    try (FileOutputStream fos = new FileOutputStream(keyPath)) {
    fos.write(encodedKey);
    System.out.println("Secret key saved to: " + keyPath);
    }
    }
  • Decryption:
    package hashFunction;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.security.Security;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    public class SHA3_256_Decryption extends javax.swing.JFrame {

    private int result;
    SecretKey clientSecretKey;
    private String keyPath = "/home/soft20/NetBeansProjects/SHA3-256/clientKey.key";

    public SHA3_256_Decryption() {
    initComponents();

    Security.addProvider(new BouncyCastleProvider());
    clientSecretKey = loadKeyFromFile(keyPath);
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    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("SHA3-256_Decryption");
    jLabel2.setText("File Path");
    jButton1.setText("Choose File");
    jButton1.addActionListener(evt -> jButton1ActionPerformed(evt));

    jLabel3.setText("File Path");
    jButton2.setText("Choose File");
    jButton2.addActionListener(evt -> jButton2ActionPerformed(evt));

    jButton3.setText("DECRYPT");
    jButton3.addActionListener(evt -> jButton3ActionPerformed(evt));

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

    jButton4.setText("SecretKey");
    jButton4.addActionListener(evt -> jButton4ActionPerformed(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 jButton2ActionPerformed(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();
    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 {
    decrypt(inputFilePath, outputFilePath, clientSecretKey);
    JOptionPane.showMessageDialog(this, "File decrypted successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

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

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

    private void decrypt(String inputFilePath, String outputFilePath, SecretKey clientSecretKey) {
    try {
    byte[] encryptedData = readFile(inputFilePath);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, clientSecretKey);
    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 void display() {
    try {
    byte[] publicKeyBytes = clientSecretKey.getEncoded();
    String res = Base64.getEncoder().encodeToString(publicKeyBytes);
    jTextArea1.setText(res);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

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

    private SecretKey loadKeyFromFile(String keyPath) {
    try (BufferedReader reader = new BufferedReader(new FileReader(keyPath))) {
    String base64Key = reader.readLine();
    byte[] decodedKey = Base64.getDecoder().decode(base64Key);
    return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    } catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Error loading secret key: " + e.getMessage());
    return null;
    }
    }
    }
Step 1
  • To start the encryption process, select the input file path after setting up the SHA3-256 encryption GUI.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes1
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes2
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 sha3-256-hash-based-key-with-aes3
Step 3
  • Select the path of the 'Encrypt.txt' file to begin the encryption process.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes4
Step 4
  • The path of the 'Encrypt.txt' file has been selected for encryption.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes5
Step 5
  • The files encrypt.txt and input.txt are chosen. When the Encrypt button is clicked, encryption is successfully finished.
  • The encrypt method reads the plain text from an input file, uses AES encryption with the provided secret key, and writes the encrypted data to an output file. It initializes the AES cipher in encryption mode and applies the doFinal method to encrypt the data. If successful, it saves the encrypted content to the specified output file and prints a confirmation message.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes6
Step 6
  • To start the decryption process, select the input file path after setting up the SHA3-256 decryption GUI.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes7
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes8
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 sha3-256-hash-based-key-with-aes9
Step 8
  • Select the path of the 'Decrypt.txt' file to begin the decryption process.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes10
Step 9
  • The path of the 'decrypt.txt' file has been selected for decryption.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes11
Step 10
  • The files encrypt.txt and decrypt.txt are chosen. When the Decrypt button is clicked, decryption is successfully finished.
  • The decrypt method reads the encrypted data from an input file, uses AES decryption with the provided secret key, and saves the decrypted content to an output file. It initializes the AES cipher in decryption mode and applies the doFinal method to decrypt the data. The decrypted content is then written to the specified output file. A success message is displayed once the decryption is complete.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes12
Step 11
  • To incorporate a secret key with sha3-256, combine the key with the input data before hashing, creating an HMAC (Hash-Based Message Authentication Code) for added integrity and authenticity.
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes13
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes14
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes15
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 sha3-256-hash-based-key-with-aes16
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes17
  • Encrypt and Decrypt data using sha3-256-hash-based-key-with-aes18