Skip to content

Instantly share code, notes, and snippets.

@navopw
Last active May 6, 2017 14:39
Show Gist options
  • Save navopw/f0ed5f783cd79e23c5d88bcc452791b7 to your computer and use it in GitHub Desktop.
Save navopw/f0ed5f783cd79e23c5d88bcc452791b7 to your computer and use it in GitHub Desktop.
AESEncryption
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryption {
private static final SecureRandom random = new SecureRandom();
private static final String ALGORITHM = "AES";
public static byte[] encrypt(String key, byte[] data) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
return AESEncryption.crypt(Cipher.ENCRYPT_MODE, key, data);
}
public static byte[] decrypt(String key, byte[] input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
return AESEncryption.crypt(Cipher.DECRYPT_MODE, key, input);
}
private static byte[] crypt(int cipherMode, String key, byte[] input) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(cipherMode, secretKey);
return cipher.doFinal(input);
}
public static String generateKey() {
int length = 16;
String alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuilder stringBuilder = new StringBuilder(length);
for (int index = 0; index < length; index++) {
stringBuilder.append(alphanumeric.charAt(AESEncryption.random.nextInt(alphanumeric.length())));
}
return stringBuilder.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment