Skip to content

Instantly share code, notes, and snippets.

@v0o0v
Created December 20, 2018 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save v0o0v/9751271ab4076ea4e42379b312534ec5 to your computer and use it in GitHub Desktop.
Save v0o0v/9751271ab4076ea4e42379b312534ec5 to your computer and use it in GitHub Desktop.
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESEncryptor {
private static final byte[] key = "1234567890123456".getBytes(StandardCharsets.UTF_8);
private static final String ALGORITHM = "AES";
public static AESEncryptor instance = new AESEncryptor();
public String encrypt(String plainText) throws Exception {
return Base64.getEncoder().encodeToString(this.encrypt(plainText.getBytes(StandardCharsets.UTF_8)));
}
public String decrypt(String encText) throws Exception {
return new String(decrypt(Base64.getDecoder().decode(encText)), StandardCharsets.UTF_8);
}
private byte[] encrypt(byte[] plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText);
}
private byte[] decrypt(byte[] cipherText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(cipherText);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment