Skip to content

Instantly share code, notes, and snippets.

@lamjar
Forked from SimoneStefani/AESenc.java
Created July 30, 2018 11:25
Show Gist options
  • Save lamjar/d0b67ee387d02d66b5e0530aabee0532 to your computer and use it in GitHub Desktop.
Save lamjar/d0b67ee387d02d66b5e0530aabee0532 to your computer and use it in GitHub Desktop.
Example of AES encryption and decryption in Java
/**
* Code written by P. Gajland
* https://github.com/GaPhil
*/
import java.security.Key;
import javax.crypto.Cipher;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import javax.crypto.spec.SecretKeySpec;
public class AESenc {
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'};
/**
* Encrypt a string with AES algorithm.
*
* @param data is a string
* @return the encrypted string
*/
public static String encrypt(String data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(data.getBytes());
return new BASE64Encoder().encode(encVal);
}
/**
* Decrypt a string with AES algorithm.
*
* @param encryptedData is a string
* @return the decrypted string
*/
public static String decrypt(String encryptedData) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
return new String(decValue);
}
/**
* Generate a new encryption key.
*/
private static Key generateKey() throws Exception {
return new SecretKeySpec(keyValue, ALGO);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment