Skip to content

Instantly share code, notes, and snippets.

@recursivecodes
Created August 15, 2019 22:25
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 recursivecodes/112b7893b08ec6311cb6519000b9a562 to your computer and use it in GitHub Desktop.
Save recursivecodes/112b7893b08ec6311cb6519000b9a562 to your computer and use it in GitHub Desktop.
Encrypt.java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
class Main {
    private static String key = "0...=="; //DEK plaintext value
    private static String initVector = "abcdefghijklmnop"; //must be 16 bytes
    public static void main(String[] args) {
        System.out.println(encrypt("hunter2"));
    }
    public static String encrypt(String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.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.getEncoder().encodeToString(encrypted);
        }
        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