import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Launch { public static void main(String[] args) throws Exception { // API key String key = "--------------------------------"; SecretKeySpec keySpec = new SecretKeySpec(readKey(key), "AES"); // Message to encrypt String msg = "{}"; // Initialize AES-CTR cipher Cipher aes = Cipher.getInstance("AES/CTR/NoPadding"); // What is the IV for phpAES's AesCtr::encrypt? byte[] iv = new byte[16]; IvParameterSpec ivSpec = new IvParameterSpec(iv); aes.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); // Encrypt text byte[] ciphertext = aes.doFinal(msg.getBytes()); // Print result System.out.println("Encrypted text: " + byteArrayToHex(ciphertext)); } // Transforms the key from a hex-formatted String to a byte array public static byte[] readKey(String key) throws Exception { byte[] returnValue; if(key.length() != 32 && key.length() != 48 && key.length() != 64) { throw new Exception("Wrong key size (only 128, 192 and 256-bit keys are accepted)."); } for(char c : key.toCharArray()) { if((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) { throw new Exception("Wrong character detected in key (expected hex string)."); } } returnValue = new byte[key.length() / 2]; for(int i = 0; i < key.length(); i += 2) { returnValue[i / 2] = (byte)((getHexDigitValue(key.charAt(i)) << 4) | getHexDigitValue(key.charAt(i + 1))); } return returnValue; } // Gets the value of a hex digit public static int getHexDigitValue(char c) { if(c >= '0' && c <= '9') { return c - '0'; } else if(c >= 'a' && c <= 'f') { return c - 'a' + 10; } else { return c - 'A' + 10; } } // Returns the string representation of a byte array public static String byteArrayToHex(byte[] byteArray) { StringBuilder sb = new StringBuilder(); for(byte b : byteArray) { sb.append(String.format("%02x", b)); } return sb.toString(); } }