-
-
Save ch3ll0v3k/dcd252267b8ccf222dd55ff292d232aa to your computer and use it in GitHub Desktop.
Java Encryption with AES
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigInteger; | |
import java.nio.charset.Charset; | |
import java.security.MessageDigest; | |
import java.util.Random; | |
import javax.crypto.Cipher; | |
import javax.crypto.spec.IvParameterSpec; | |
import javax.crypto.spec.SecretKeySpec; | |
import org.apache.commons.codec.binary.Base64; | |
public class Crypto { | |
private static final String KEY = "u12hUPtyGhg5WR3t"; | |
private static final String INIT_VECTOR = "RandomInitVector"; | |
public static String encryptAES(String value) { | |
try { | |
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8")); | |
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES"); | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); | |
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); | |
byte[] encrypted = cipher.doFinal(value.getBytes()); | |
return Base64.encodeBase64String(encrypted); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
return null; | |
} | |
public static String decryptAES(String encrypted) { | |
try { | |
IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes("UTF-8")); | |
SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES"); | |
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); | |
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); | |
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted)); | |
return new String(original); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment