Kensoft PH
  • Download
  • Contact
  • About
Java Quiz
No Result
View All Result
Kensoft PH
  • Download
  • Contact
  • About
Java Quiz
No Result
View All Result
Kensoft PH
No Result
View All Result
Home Java

How to use AES and 3DES in Java | 100% best for beginners

May 2, 2021 - Updated on September 23, 2022
in Java
Reading Time: 5 mins read
2
3DES in Java and AES in Java
1.2k
VIEWS
Share on FacebookShare on TwitterShare via Email

Contents

  • JavaFX Tutorial
  • Advanced Encryption Standard (AES in Java)
    • Encryption
    • Decryption
  • Triple Data Encryption Standard (3DES in Java)
    • 3DES in Java Encryption
    • Decryption
  • Source Code
  • Output
  • YouTube Video

JavaFX Tutorial

In this tutorial, you will learn Encryption and Decryption using Advanced Encryption Standard AES in Java and Triple Data Encryption Standard – 3DES in Java. Advanced Encryption Standard (AES) is a widely adopted symmetric encryption algorithm nowadays. It is also known by its original name Rijndael. 3DES in Java/Triple DES, officially the Triple Data Encryption Algorithm. Triple DES or 3DES in Java applies the Data Encryption Standard (DES) cipher algorithm and also, Triple DES or 3DES in Java is a symmetric-key block cipher.

Advanced Encryption Standard (AES in Java)

Encryption

byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec keyspec = new PBEKeySpec(aesSECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey sk = factory.generateSecret(keyspec);
SecretKeySpec secretKeyspec = new SecretKeySpec(sk.getEncoded(), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeyspec, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));

Decryption

byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec keyspec = new PBEKeySpec(aesSECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey sk = factory.generateSecret(keyspec);
SecretKeySpec secretKeyspec = new SecretKeySpec(sk.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKeyspec, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(data)));

Triple Data Encryption Standard (3DES in Java)

3DES in Java Encryption

byte[] encryptKey = txt_key.getText().getBytes();
DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey theKey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec IvParameters = new IvParameterSpec(new byte[]{12, 34, 56, 78, 90, 87, 65, 43});
cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
byte[] encrypted = cipher.doFinal(txt_data.getText().getBytes());
String txt = Base64.getEncoder().encodeToString(encrypted);
txtArea_result.setText(txt);

Decryption

byte[] encryptKey = txt_key.getText().getBytes();
DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey theKey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec ivParameters = new IvParameterSpec(new byte[]{12, 34, 56, 78, 90, 87, 65, 43});
cipher.init(Cipher.DECRYPT_MODE, theKey, ivParameters);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(txt_data.getText().getBytes()));
String dec = new String(original);
txtArea_result.setText(dec);

Source Code

import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
* FXML Controller class
*
* @author KENSOFT
*/
public class FX_EncryptionController implements Initializable {

@FXML
private TextField txt_data;
@FXML
private TextField txt_key;
@FXML
private TextArea txtArea_result;
@FXML
private Button btn_encrypt;
@FXML
private Button btn_decrypt;
@FXML
private RadioButton radio_aes;
@FXML
private RadioButton radio_3des;

private static final String SALT = "ThisIsSalt";
private static Cipher cipher;

@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}

public static String AESencrypt(String data, String aesSECRET_KEY) {
try {
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec keyspec = new PBEKeySpec(aesSECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey sk = factory.generateSecret(keyspec);
SecretKeySpec secretKeyspec = new SecretKeySpec(sk.getEncoded(), "AES");

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeyspec, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)));
} catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) {
System.out.println(e);
}
return null;
}

public static String AESdecrypt(String data, String aesSECRET_KEY) {
try {
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec keyspec = new PBEKeySpec(aesSECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
SecretKey sk = factory.generateSecret(keyspec);
SecretKeySpec secretKeyspec = new SecretKeySpec(sk.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKeyspec, ivspec);
return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
} catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) {
System.out.println(e);
}
return null;
}

public String TDESencrypt() throws Exception {
byte[] encryptKey = txt_key.getText().getBytes();
DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey theKey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec IvParameters = new IvParameterSpec(new byte[]{12, 34, 56, 78, 90, 87, 65, 43});
cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
byte[] encrypted = cipher.doFinal(txt_data.getText().getBytes());
String txt = Base64.getEncoder().encodeToString(encrypted);
txtArea_result.setText(txt);
return null;
}

public String TDESdecrypt() throws Exception {
byte[] encryptKey = txt_key.getText().getBytes();
DESedeKeySpec spec = new DESedeKeySpec(encryptKey);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey theKey = keyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
IvParameterSpec ivParameters = new IvParameterSpec(new byte[]{12, 34, 56, 78, 90, 87, 65, 43});
cipher.init(Cipher.DECRYPT_MODE, theKey, ivParameters);
byte[] original = cipher.doFinal(Base64.getDecoder().decode(txt_data.getText().getBytes()));
String dec = new String(original);
txtArea_result.setText(dec);
return null;
}

@FXML
private void buttonEncrypt(MouseEvent event) throws Exception {
if (txt_key.getText().trim().isEmpty() && txt_data.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Key and Data cannot be empty");
alert.setHeaderText(null);
alert.setTitle("Encrypt");
alert.showAndWait();
} else if (txt_key.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Key cannot be empty");
alert.setHeaderText(null);
alert.setTitle("Encrypt");
alert.showAndWait();
} else if (txt_data.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Data cannot be empty");
alert.setHeaderText(null);
alert.setTitle("Encrypt");
alert.showAndWait();
} else {
if (radio_aes.isSelected()) {
txtArea_result.setText(AESencrypt(txt_data.getText(), txt_key.getText()));
} else if (radio_3des.isSelected()) {
if (txt_key.getText().length() <= 23) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please add your key");
alert.setHeaderText("Wrong key size");
alert.setTitle("Encrypt");
alert.showAndWait();
} else {
TDESencrypt();
}
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please select an Encryption type");
alert.setHeaderText(null);
alert.setTitle("Encrypt");
alert.showAndWait();
}
}
}

@FXML
private void buttonDecrypt(MouseEvent event) throws Exception {
if (txt_key.getText().trim().isEmpty() && txt_data.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Key and Data cannot be empty");
alert.setHeaderText(null);
alert.setTitle("Decrypt");
alert.showAndWait();
} else if (txt_key.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Key cannot be empty");
alert.setHeaderText(null);
alert.setTitle("Decrypt");
alert.showAndWait();
} else if (txt_data.getText().trim().isEmpty()) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Data cannot be empty");
alert.setHeaderText(null);
alert.setTitle("Decrypt");
alert.showAndWait();
} else {
if (radio_aes.isSelected()) {
txtArea_result.setText(AESdecrypt(txt_data.getText(), txt_key.getText()));
} else if (radio_3des.isSelected()) {
TDESdecrypt();
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("Please select an Encryption type");
alert.setHeaderText(null);
alert.setTitle("Decrypt");
alert.showAndWait();
}
}
}

@FXML
private void radio_aes(MouseEvent event) {
radio_3des.setSelected(false);
}

@FXML
private void radio_tdes(MouseEvent event) {
radio_aes.setSelected(false);
}
}

Output

3DES in Java and AES in Java

 

YouTube Video

JavaFX Tutorial: Triple DES and AES in Java 2021
Watch this video on YouTube.
Previous Post

JavaFX Alert Dialogs | 100% best for beginners

Next Post

How to customize the JavaFX Tooltip | 100% best for beginners

KENSOFT

KENSOFT

What’s up! Kent is my name. The name KENSOFT is derived from the words Kent and Software. My programming language of choice is Java

Related tutorials

How to use the JavaFX ToolBar
Java

How to use the JavaFX ToolBar | 100% Perfect Tutorial

January 24, 2023
13
JavaFX Context Menu
Java

How to use the JavaFX ContextMenu | 100% Perfect Tutorial

January 22, 2023
10
JavaFX MenuBar
Java

How to use the Menu Bar in JavaFX | 100% Perfect Tutorial

December 3, 2022 - Updated on January 23, 2023
76
Next Post
How to customize the JavaFX Tooltip | 100% best for beginners

How to customize the JavaFX Tooltip | 100% best for beginners

show the JavaFX scene

How to show the JavaFX scene tutorial | 100% best for beginners

change the stage icon in JavaFX

How to change the stage icon in JavaFX | 100% best for beginners

Comments 2

  1. Avatar of Ely Ely says:
    1 year ago

    Could you provide the fxml too? It’s hard to try and link it with my own fxml I created in scene builder.

    0
    0
    Reply
    • Avatar of KENSOFT KENSOFT says:
      1 year ago

      Hello, You can download the project here: https://www.buymeacoffee.com/kensoftph/e/42129

      0
      0
      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Maximum upload file size: 20 MB. You can upload: image, audio, video, document, text. Drop files here

  • Trending
  • Comments
  • Latest
Failed to automatically set up a JavaFX Platform

Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

April 11, 2021 - Updated on July 3, 2022
MySQL database using XAMPP

How to connect Java to MySQL database using Xampp server | 100% best for beginners

October 27, 2020 - Updated on January 23, 2023
JavaFX 17

How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

November 15, 2021 - Updated on December 13, 2021
change the stage icon in JavaFX

How to change the stage icon in JavaFX | 100% best for beginners

May 23, 2021 - Updated on September 24, 2022
Failed to automatically set up a JavaFX Platform

Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

send SMS in java

How to send SMS in Java | 100% best example

3DES in Java and AES in Java

How to use AES and 3DES in Java | 100% best for beginners

JavaFX Splash Screen

How to create JavaFX Splash Screen | 100% best for beginners

How to use the JavaFX ToolBar

How to use the JavaFX ToolBar | 100% Perfect Tutorial

January 24, 2023
JavaFX Context Menu

How to use the JavaFX ContextMenu | 100% Perfect Tutorial

January 22, 2023
JavaFX MenuBar

How to use the Menu Bar in JavaFX | 100% Perfect Tutorial

December 3, 2022 - Updated on January 23, 2023
How to use the Slider in JavaFX | 100% Perfect Tutorial

How to use the Slider in JavaFX | 100% Perfect Tutorial

November 27, 2022

Latest Tutorials

How to use the JavaFX ToolBar

How to use the JavaFX ToolBar | 100% Perfect Tutorial

January 24, 2023
JavaFX Context Menu

How to use the JavaFX ContextMenu | 100% Perfect Tutorial

January 22, 2023
JavaFX MenuBar

How to use the Menu Bar in JavaFX | 100% Perfect Tutorial

December 3, 2022 - Updated on January 23, 2023

Popular Tutorials

  • Failed to automatically set up a JavaFX Platform

    Failed to automatically set up a JavaFX Platform SOLVED Apache NetBeans 12.3 | Best way

    0 shares
    Share 0 Tweet 0
  • How to connect Java to MySQL database using Xampp server | 100% best for beginners

    0 shares
    Share 0 Tweet 0
  • How To install JDK 17 and JavaFX 17 on NetBeans IDE | Best

    0 shares
    Share 0 Tweet 0
Facebook Instagram Youtube Github LinkedIn Discord
Kensoft PH

What’s up! Kent is my name. The name KENSOFT is derived from the words Kent and Software. My programming language of choice is Java, which I use to create computer applications. In a company, I created applications and a website.

Website

Privacy Policy

Terms and Condition

Sitemap

Services

Guest Post

Fiverr

Freelancer

Upwork

Categories

Website Status

Check the status

Latest Tutorials

How to use the JavaFX ToolBar

How to use the JavaFX ToolBar | 100% Perfect Tutorial

January 24, 2023
JavaFX Context Menu

How to use the JavaFX ContextMenu | 100% Perfect Tutorial

January 22, 2023
JavaFX MenuBar

How to use the Menu Bar in JavaFX | 100% Perfect Tutorial

December 3, 2022 - Updated on January 23, 2023

© 2023 Made With Love By KENSOFT PH

No Result
View All Result
  • Download
  • Java Quiz
  • Contact
  • About

© 2023 Made With Love By KENSOFT PH

This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.