In Java 8 we have got new classes in java.util package for Base64 encoding and decoding. It is important to encode the binary data with Base64 to ensure it to be intact without modification when it is stored or transferred.
EncryptionDecryptionAES.java:
------------------------------------------------------------------------
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class EncryptionDecryptionAES {
static Cipher cipher;
public static void main(String[] args) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
cipher = Cipher.getInstance("AES");
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);
}
public static String encrypt(String plainText, SecretKey secretKey)
throws Exception {
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;
}
public static String decrypt(String encryptedText, SecretKey secretKey)
throws Exception {
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;
}
}
If you are using lesser version of java, just add Base64decoder.jar in your project. and do the encryption and decryption in files like below.
EncryptionDecryption.java:
-------------------------------------------------------------
import java.io.*;
import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;
public class EncryptionDecryption
{
public static void main(String[] args)
{
File file = null;
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
file = new File("Hello.txt");
fis = new FileInputStream(file.getAbsolutePath());
BASE64Encoder encoder=new BASE64Encoder();
file=new File("Encoded.txt");
fos=new FileOutputStream(file.getAbsoluteFile());
encoder.encode(fis,fos);
File decodedFile=new File("Decoded.txt");
fos=new FileOutputStream(decodedFile.getAbsoluteFile());
BASE64Decoder decoder=new BASE64Decoder();
decoder.decodeBuffer(new FileInputStream(file.getAbsolutePath()), fos);
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
Similarly you can do the same with jsp, for file uploading in jsp refer below link:
Upload File in struts2.0- Click Here
upload file in spring MVC- Click Here