Aes java encrypt decrypt

Java AES Encryption Decryption Example

Java support many secure encryption algorithms but some of them are weak to be used in security-intensive applications. For example, the Data Encryption Standard (DES) encryption algorithm is considered highly insecure; messages encrypted using DES have been decrypted by brute force within a single day by machines such as the Electronic Frontier Foundation’s (EFF) Deep Crack.

A more secure encryption algorithm is AES – Advanced Encryption Standard which is a symmetric encryption algorithm. AES encryption is used by the U.S. for securing sensitive but unclassified material, so we can say it is enough secure.

1. AES Encryption and Decryption

Let’s see an example of using AES encryption in this java program.

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class AES < private static SecretKeySpec secretKey; private static byte[] key; public static void setKey(final String myKey) < MessageDigest sha = null; try < key = myKey.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); >catch (NoSuchAlgorithmException | UnsupportedEncodingException e) < e.printStackTrace(); >> public static String encrypt(final String strToEncrypt, final String secret) < try < setKey(secret); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.getEncoder() .encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); >catch (Exception e) < System.out.println("Error while encrypting: " + e.toString()); >return null; > public static String decrypt(final String strToDecrypt, final String secret) < try < setKey(secret); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher.doFinal(Base64.getDecoder() .decode(strToDecrypt))); >catch (Exception e) < System.out.println("Error while decrypting: " + e.toString()); >return null; > >

2. Encryption and decryption example

Let’s test if we are able to get the decrypted string back from the encrypted string.

final String secretKey = "ssshhhhhhhhhhh. "; String originalString = "howtodoinjava.com"; String encryptedString = AES.encrypt(originalString, secretKey) ; String decryptedString = AES.decrypt(encryptedString, secretKey) ; System.out.println(originalString); System.out.println(encryptedString); System.out.println(decryptedString);
howtodoinjava.com Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o= howtodoinjava.com

Drop me your question and comments below.

Источник

Implementing AES Encryption And Decryption In Java

Data encryption is an important feature in data protection. There are various methods used to encrypt and decrypt data to enhance the safety of data transmitted.

In this article, we will look at AES as a method of data encryption and decryption. AES, Advanced Encryption Standard is a block ciphertext encryption and decryption algorithm that processes a block of 128 bits of data using secret keys of 128, 192, or 256 bits.

We will also discuss how this algorithm can be implemented using the Java programming language.

Table of contents

Prerequisites

For a better understanding of this article, you will need:

An overview of AES algorithm

AES is a 128-bit symmetric block ciphertext. This algorithm uses substitution and permutations; known as the SP networks . It consists of multiple texts to produce a ciphertext. AES performs its calculations in the form of byte data instead of bit data.

Читайте также:  Ошибка установки python 0x80070661

This means that AES treats 128 bits of a clear text block as 16 bytes. The number of rounds during the encryption process depends on the key size being used. For example:

  • The 128-bit key size uses 10 rounds.
  • The 192-bit key size uses 12 rounds.
  • The 256-bit key size uses 14 rounds.

Data to be encrypted is stored in a 4 by 4 matrix format called the state array. Each output takes a state array as input and gives a similar array as output.

In a 16-bytes matrix, each cell represents 1-byte, this means that four cells which is the equivalent of four bytes represent one word, implying that each state array has four words.

Java imports

In our program to create the AES algorithm, we will import the following Java packages:

import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; import java.util.Base64; 

AES implementation in Java

In this section, we will be implementing AES in Java language. We will start by creating a Java class and name it AES_ENCRYPTION . In our class, we will create an init method. This method will create the encryption keys.

In this method, using a key generator, we will generate one key. We will get the key generator instance of AES and assign it to keyGenerator . We are then required to initialize the key size. The key sizes values can be 128, 192 or 256 bytes.

For this guide, we shall be using a key size value of 128 bytes.

The code below can be used to implement this:

public class AES_ENCRYPTION   private SecretKey key;  private final int KEY_SIZE = 128;  private final int DATA_LENGTH = 128;  private Cipher encryptionCipher;   public void init() throws Exception   KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");  keyGenerator.init(KEY_SIZE);  key = keyGenerator.generateKey();  > 

Encryption

Now that we have initialized our keys, we will start encrypting. First, we will create an encrypt method and pass in the data that is to be encrypted.

Then we guess the byte array from this message, create an encryption cipher and get its instance.

Next, we initialize the encryption cipher with the init method, using the Cipher.ENCRYPT_MODE and pass in a parameter which is the key that we have generated.

Finally, we create a method encryptionCipher that will return a byte array of the encrypted data. The encrypt method returns the encrypted data in bytes:

public String encrypt(String data) throws Exception   byte[] dataInBytes = data.getBytes();  encryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");  encryptionCipher.init(Cipher.ENCRYPT_MODE, key);  byte[] encryptedBytes = encryptionCipher.doFinal(dataInBytes);  return encode(encryptedBytes);  > 

Decryption

To decrypt the data we encrypted in the encrypt method above, we will create the decrypt method and pass in the encrypted data as parameters. We also need to convert our data to a byte array again and decode it since we encoded it during encryption.

We will then create a decryption cipher and get its instance of the AES algorithm. We then initialize the decryption cipher with the init method using the decrypt mode. This takes the same key that was used in encryption as parameters.

Afterwards, we can get our bytes array from the decrypted bytes from the decryptionCipher.doFinal() method, and return the new string of the decrypted bytes. We will use the code below:

 public String decrypt(String encryptedData) throws Exception   byte[] dataInBytes = decode(encryptedData);  Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");  GCMParameterSpec spec = new GCMParameterSpec(DATA_LENGTH, encryptionCipher.getIV());  decryptionCipher.init(Cipher.DECRYPT_MODE, key, spec);  byte[] decryptedBytes = decryptionCipher.doFinal(dataInBytes);  return new String(decryptedBytes);  > 

Encoding and decoding

To convert our data into a string, we will use a private method called encode and decode that will take in the bytes array and returns to BASE64 . We will use the code below for both encoding and decoding:

private String encode(byte[] data)   return Base64.getEncoder().encodeToString(data);  >   private byte[] decode(String data)   return Base64.getDecoder().decode(data);  > 

Java main method

From the steps above, we have the encryption and the decryption algorithm. Now the main thing to do to make sure that our algorithm is working properly is implementing the two methods in the main method.

In main method, we will put everything in the try … catch block. In this method, we will initialize our algorithm, initialize the variable that will be used to hold the encrypted message and the decrypted data, and pass in the data to be decrypted.

The last task in our program is to print out the data and the decrypted data in our terminal. The code snippet below is used in the main method:

public static void main(String[] args)   try   AES_ENCRYPTION aes_encryption = new AES_ENCRYPTION();  aes_encryption.init();  String encryptedData = aes_encryption.encrypt("Hello, welcome to the encryption world");  String decryptedData = aes_encryption.decrypt(encryptedData);   System.out.println("Encrypted Data : " + encryptedData);  System.out.println("Decrypted Data : " + decryptedData);  > catch (Exception ignored)   >  > > 

Conclusion

With Java cryptography, it is easy to develop an algorithm that can be used to protect our data from unauthorized access. This is enabled by the Java packages that allows the user to import and develop an algorithm that they can use.

For example, in this tutorial, with the use of appropriate Java packages, we have developed an AES algorithm to protect our data.

Peer Review Contributions by: Monica Masae

Источник

Java AES-256 Encryption and Decryption

Learn to use Java AES-256 bit encryption to create secure passwords and decryption for password validation. To read simple AES encryption, read the linked post.

1. AES – Advanced Encryption Standard

AES is a symmetric encryption algorithm. It was intended to be easy to implement in hardware and software, as well as in restricted environments and offer good defenses against various attack techniques.

AES is block cipher capable of handling 128 bit blocks, using keys sized at 128, 192, and 256 bits. Each cipher encrypts and decrypts data in blocks of 128 bits using cryptographic keys of 128-, 192- and 256-bits, respectively.

It uses the same key for encryption and decryption processes, so the sender and the receiver, both must know — and use — the same secret key.

In given encryption and decryption example, I have used base64 encoding in UTF-8 charset. It is done for displaying the output of program.

In your application, you can store and validate the data in byte array format as well.

Java program to encrypt a password (or any information) using AES 256 bits.

import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.spec.KeySpec; import java.util.Base64; public class AES256 < private static final String SECRET_KEY = "my_super_secret_key"; private static final String SALT = "ssshhhhhhhhhhh. "; public static String encrypt(String strToEncrypt) < try < byte[] iv = ; IvParameterSpec ivspec = new IvParameterSpec(iv); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec); return Base64.getEncoder() .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); > catch (Exception e) < System.out.println("Error while encrypting: " + e.toString()); >return null; > >

Do not forget to use the same secret key and salt in encryption and decryption.

Java program to decrypt a password (or any information) using AES 256 bits.

import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.spec.KeySpec; import java.util.Base64; public class AES256 < private static final String SECRET_KEY = "my_super_secret_key"; private static final String SALT = "ssshhhhhhhhhhh. "; public static String decrypt(String strToDecrypt) < try < byte[] iv = ; IvParameterSpec ivspec = new IvParameterSpec(iv); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256); SecretKey tmp = factory.generateSecret(spec); SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec); return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); > catch (Exception e) < System.out.println("Error while decrypting: " + e.toString()); >return null; > >

Let’s test our AES256 encryption and decryption methods with a simple string.

public class AES256Example < public static void main(String[] args) < String originalString = "howtodoinjava.com"; String encryptedString = AES256.encrypt(originalString); String decryptedString = AES256.decrypt(encryptedString); System.out.println(originalString); System.out.println(encryptedString); System.out.println(decryptedString); >>
howtodoinjava.com BfNFPRgfKF8Ke9kpoNAagmcI4/Hya5o/rq9/fq97ZiA= howtodoinjava.com

Clearly, we are able to use AES256 encryption to encrypt a string, and decryption to get back the original string from the encrypted string.

Источник

Оцените статью