Skip to content

Instantly share code, notes, and snippets.

@naikrovek
Last active April 29, 2020 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save naikrovek/d3b2cc302ed55a36be15 to your computer and use it in GitHub Desktop.
Save naikrovek/d3b2cc302ed55a36be15 to your computer and use it in GitHub Desktop.
AES Encryption in Java.
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES128Cipher {
private static String key = "123123123123123123123123"; // use your own
private static byte[] ivBytes = {
// use your own.
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
public static String encrypt(String text) throws java.io.UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {
byte[] keyBytes = key.getBytes();
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
byte[] encryptedBytes = cipher.doFinal(text.getBytes("UTF-8"));
return Base64.encodeBase64String(encryptedBytes);
}
public static String decrypt(String text) throws java.io.UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {
byte[] textBytes = Base64.decodeBase64(text);
byte[] keyBytes = key.getBytes();
AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
byte[] decodedBytes = cipher.doFinal(textBytes);
return new String(decodedBytes, "UTF-8");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment