Encrypt / decrypt with AES256 in PHP and Java

thank you for your hard work! I'm Ishiguro from GMO Research!

By the way, I think that you may suddenly be urged to encrypt with AES. For those of you, this time we will write encryption / composite code in a total of three ways: Java and PHP, PHP is OpenSSL and Mcrypt. It is implemented with AES256 algorithm, ECB mode, PKCS5 padding.


Java 1.8 PHP 5.6


By default, Java can only handle AES key lengths of 128 bits. In order to handle 256bit keys, it is necessary to replace the Java policy file.

For details, refer to articles such as Making AES256 available in Java.


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class aes01 {

	public static void main(String[] args) {
		try {
			byte[] key = DatatypeConverter.parseBase64Binary(
                    "Base64 encoded string of keys");
			SecretKeySpec sks = new SecretKeySpec(key, "AES");

			byte[] input = "The string you want to encrypt".getBytes();

			Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
			c.init(Cipher.ENCRYPT_MODE, sks);
			byte encrypted[] = c.doFinal(input);


			c.init(Cipher.DECRYPT_MODE, sks);
			byte decrypted[] = c.doFinal(encrypted);

			System.out.println(new String(decrypted));
		} catch (Exception e) {


Encryption with PHP 5.3 or later is done with OpenSSL.


$key = base64_decode("Base64 encoded string of keys");

$input = 'The string you want to encrypt';

$encrypted = openssl_encrypt($input, 'aes-256-ecb', $key);

echo $encrypted;

$decrypted = openssl_decrypt($encrypted, 'aes-256-ecb', $key);

echo $decrypted;

PHP (Mcrypt) * Not recommended

Encryption in a deprecated way. Do not use it except when necessary. Or rather, it's too annoying.


$key = base64_decode('Base64 encoded string of keys');

$input = 'The string you want to encrypt';

$crypt = new Crypt($key);

$encrypted = base64_encode($crypt->encrypt($input));

echo $encrypted;

$decrypted = $crypt->decrypt(base64_decode($encrypted));

echo $decrypted;

class Crypt {

    private $__encrypt_key = null;

    public $iv = null;

    public function __construct($encrypt_key) {
        $this->__encrypt_key = $encrypt_key;

    public function encrypt($input, $algo = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_ECB) {
        list($size, $td) = $this->__open($algo, $mode);
        $input = $this->__pkcs5Pad($input, $size);
        $data = mcrypt_generic($td, $input);
        return $data;

    public function decrypt($input, $algo = MCRYPT_RIJNDAEL_128, $mode = MCRYPT_MODE_ECB) {
        list ($size, $td) = $this->__open($algo, $mode);
        $input = mdecrypt_generic($td, $input);
        $data = $this->__pkcs5Unpad($input);
        return $data;

    private function __open($algo, $mode) {
        $size = mcrypt_get_block_size($algo, $mode);
        $td = mcrypt_module_open($algo, '', $mode, '');
        $this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $this->__encrypt_key, $this->iv);
        return array($size, $td);

    private function __close($td){

    public static function __pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);

    public static function __pkcs5Unpad($text) {
        $pad = ord($text{strlen($text)-1});
        if ($pad > strlen($text)) return false;
        if (strspn($text, chr($pad), strlen($text) - $pad) !== $pad) return false;
        return substr($text, 0, -1 * $pad);

MCRYPT_RIJNDAEL_128 seems to be equivalent to AES256. There is also an algorithm called MCRYPT_RIJNDAEL_256, but note that this is not the case.

For the time being, it is possible to change the algorithm and mode so that it can be used universally, I'm not sure if it really works.

in conclusion

that's all! It's okay to be driven by the urge to AES encrypt.

I'm glad that PHP's OpenSSL is very simple. (Small feeling)

Recommended Posts

Encrypt / decrypt with AES256 in PHP and Java
Encrypt with Java and decrypt with C #
How to encrypt and decrypt with RSA public key in Java
[Java] How to encrypt with AES encryption with standard library
Store in Java 2D map and turn with for statement
Log aggregation and analysis (working with AWS Athena in Java)
I compared PHP and Java constructors
Morphological analysis in Java with Kuromoji
Use java with MSYS and Cygwin
Distributed tracing with OpenCensus and Java
Encoding and Decoding example in Java
Use JDBC with Java and Scala.
Implement PHP implode function in Java
StringBuffer and StringBuilder Class in Java
Output PDF and TIFF with Java 8
Play with Markdown in Java flexmark-java
Hello world in Java and Gradle
Compare Hello, world! In Spring Boot with Java, Kotlin and Groovy
Difference between final and Immutable in Java
Monitor Java applications with jolokia and hawtio
Differences in writing in Ruby, PHP, Java, JS
Link Java and C ++ code with SWIG
Achieve OpenSSL compatible encryption with Java / PHP
Let's try WebSocket with Java and javascript!
[Java] for Each and sorted in Lambda
[Java] Reading and writing files with OpenCSV
HTTPS with Spring Boot and Let's Encrypt
Read xlsx file in Java with Selenium
I wrote a Lambda function in Java and deployed it with SAM
Split a string with ". (Dot)" in Java
Arrylist and linked list difference in java
Working with huge JSON in Java Lambda
Program PDF headers and footers in Java
Learn Flyweight patterns and ConcurrentHashMap in Java
Java Direction in C ++ Design and Evolution
Java to C and C to Java in Android Studio
Reading and writing gzip files in Java
Difference between int and Integer in Java
Discrimination of Enums in Java 7 and above
Be careful with requests and responses when using the Serverless Framework in Java
Regarding the transient modifier and serialization in Java
Create barcodes and QR codes in Java PDF
Detect similar videos in Java and OpenCV rev.2
Create a CSR with extended information in Java
Refactored GUI tools made with Java8 + JavaFX in 2016
Static code analysis with Checkstyle in Java + Gradle
Parallel and parallel processing in various languages (Java edition)
Difference between next () and nextLine () in Java Scanner
Build and test Java + Gradle applications with Wercker
Try to link Ruby and Java with Dapr
JSON with Java and Jackson Part 2 XSS measures
Differences in writing Java, C # and Javascript classes
Text extraction in Java from PDF with pdfbox-2.0.8
Capture and save from selenium installation in Java
Detect similar videos in Java and OpenCV rev.3
Add, read, and delete Excel comments in Java
Check static and public behavior in Java methods
[Java] Understand in 10 minutes! Associative array and HashMap
Basics of threads and Callable in Java [Beginner]
Prepare a scraping environment with Docker and Java
Practice working with Unicode surrogate pairs in Java