Encryption and Decryption of Data using AES-128 algorithm in Java
Encryption allows the user to obfuscate data through a code that can only be decrypted by the user or other trusted individuals. Not surprisingly, programming languages such as Java that are used for managing network traffic and network interfaces have built-in libraries to support data encryption. Many encryption standards exist in the Java libraries, including the AES 128 standard.
Examples
A simple Java coding example displays how to use encryption and decryption libraries with the AES 128 specification. The following shows how to create encryption, decryption, key and cipher objects in Java to encrypt & decrypt a message.
package simplecodestuffs;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.*;
import sun.misc.*;
public class AES {
private static final String ALGO = "AES";
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher chiper = Cipher.getInstance(ALGO);
chiper.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = chiper.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher chiper = Cipher.getInstance(ALGO);
chiper.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = chiper.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
We use “generateKey()” method to generate a secret key for AES algorithm with a given key.
Below is the code how you can use the above encryption algorithm.
package simplecodestuffs;
public class Checker {
public static void main(String[] args) throws Exception {
String password = "mypassword";
String passwordEnc = AES.encrypt(password);
String passwordDec = AES.decrypt(passwordEnc);
System.out.println("Plain Text : " + password);
System.out.println("Encrypted Text : " + passwordEnc);
System.out.println("Decrypted Text : " + passwordDec);
}
}
Interesting articles on information like this is a great find. It’s like finding a treasure. I appreciate how you express your many points and share in your views. Thank you.
This is one awesome blog.Really thank you! Great.