Skip to content

Instantly share code, notes, and snippets.

@fajarlabs
Created May 24, 2017 08:25
Show Gist options
  • Save fajarlabs/e8ecb11a7403388a451e54498142a931 to your computer and use it in GitHub Desktop.
Save fajarlabs/e8ecb11a7403388a451e54498142a931 to your computer and use it in GitHub Desktop.
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import util.B64;
public class Crypt {
public static void main(String[] args) throws Exception {
// Receive Key
String KEY = "57238004e784498bbc2f8bf984565090";
// Message
String MSG = "HELLO WORLD";
// Example
String encrypt = encrypt(MSG, KEY);
String decrypt = decrypt(B64.dec(encrypt), B64.enc(KEY));
}
public static String encrypt(String msg, String keyHexString) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(keyHexString), "AES");
cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
byte[] encrypted = cipher.doFinal(msg.getBytes());
return new String(B64.enc(byteArrayToHexString(encrypted)));
}
public static String decrypt(String msg64String, String keyHex64String) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(B64.dec(keyHex64String)), "AES");
cipher.init(Cipher.DECRYPT_MODE, sks, cipher.getParameters());
byte[] encrypted = cipher.doFinal(hexStringToByteArray(msg64String));
return new String(encrypted);
}
public static byte[] hexStringToByteArray(String s) {
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}
public static String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment