← Back to list

Encryption/Decryption with AES 256 Algorithm in Java and PHP

Hi everyone, this article helps you to implement AES 256 Encryption and Decryption algorithm in Java and PHP. I implemented the algorithm…

Kanmit Owolabi · 2024-06-09 11:22 · 0 claps · 2.0 min read
#aes-encryption #aes-256-cbc #decryption-api #encryption-decryption
Open on Medium ↗
Wiki topics: 💻 · Programming 🔒 · Cybersecurity

Encryption/Decryption with AES 256 Algorithm in Java and PHP

Hi everyone, this article helps you to implement AES 256 Encryption and Decryption algorithm in Java and PHP. I implemented the algorithm for a request that needs to be consumed by a third-party vendor at my workplace.

Photo by Jaye Haych on Unsplash

Photo by Jaye Haych on Unsplash

My application was developed in Java (my part is to decrypt the encrypted-value passed from another system to my service for further processing) but they were unable to efficiently test the encrypt and decrypt equivalent of the method I shared with them (for context — their system is developed in PHP)

I had to assist in developing both Java and PHP code snippets of the algorithm. Kindly, find the methods below:

Java Implementation

package com.example;

import com.configurations.EncryptionProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

@Service
public class AesEncryptionUtil {
    private static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS5PADDING";

    private final String initializationVector;

    @Autowired
    private EncryptionProperties encryptionProperties;

    public AesEncryptionUtil(EncryptionProperties encryptionProperties) {
        String initializationVector = encryptionProperties.getInitializationVector();
        // Ensure the IV is exactly 16 bytes (128 bits) by truncating or padding
        if (initializationVector.length() >= 16) {
            this.initializationVector = initializationVector.substring(0, 16);
        } else {
            this.initializationVector = String.format("%-16s", initializationVector).replace(' ', '\0');
        }
    }

    public String encrypt(String value, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec iv = new IvParameterSpec(initializationVector.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public String decrypt(String encrypted, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        IvParameterSpec iv = new IvParameterSpec(initializationVector.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
        return new String(original);
    }
}

PHP Implementation

<?php

class EncryptionProperties {
    private string $initializationVector;

    public function getInitializationVector(): string {
        return $this->initializationVector;
    }

    public function setInitializationVector(string $initializationVector): void {
        // Ensure the IV is exactly 16 bytes (128 bits) by truncating or padding
        $this->initializationVector = substr($initializationVector, 0, 16);
    }
}

class AesEncryptionUtil {
    private const ENCRYPTION_ALGORITHM = 'AES-256-CBC';
    private EncryptionProperties $encryptionProperties;

    public function __construct(EncryptionProperties $encryptionProperties) {
        $this->encryptionProperties = $encryptionProperties;
    }

    public function encrypt(string $value, string $key): string {
        $iv = $this->encryptionProperties->getInitializationVector();
        $encrypted = openssl_encrypt($value, self::ENCRYPTION_ALGORITHM, $key, OPENSSL_RAW_DATA, $iv);
        return urlencode(base64_encode($encrypted));
    }

    public function decrypt(string $encrypted, string $key): string {
        $iv = $this->encryptionProperties->getInitializationVector();
        $decrypted = openssl_decrypt(base64_decode(urldecode($encrypted)), self::ENCRYPTION_ALGORITHM, $key, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }
}

// Example key and initialization vector (IV) - replace these with your actual values
$key = 'the-secret-key-comes-here';
$iv = 'the-initialization-vector-comes-here';
$value = 'the-value-to-encrypt-comes-here';

// Create an instance of EncryptionProperties
$encryptionProperties = new EncryptionProperties();

// Set the initialization vector
$encryptionProperties->setInitializationVector($iv);

// Create an instance of AesEncryptionUtil
$aesEncryptionUtil = new AesEncryptionUtil($encryptionProperties);

// Encrypt the value
$encryptedValue = $aesEncryptionUtil->encrypt($value, $key);
echo "Encrypted value: $encryptedValue\n";

// Decrypt the encrypted value
$decryptedValue = $aesEncryptionUtil->decrypt($encryptedValue, $key);
echo "Decrypted value: $decryptedValue\n";

I hope this helps someone. Thanks!


메타데이터
post_id
acba92faeeb1
slug
encryption-decryption-with-aes-256-algorithm-in-java-and-php-acba92faeeb1
url
https://medium.com/@kanmitowolabi/encryption-decryption-with-aes-256-algorithm-in-java-and-php-acba92faeeb1
canonical_url
https://medium.com/@kanmitowolabi/encryption-decryption-with-aes-256-algorithm-in-java-and-php-acba92faeeb1
author_url
https://medium.com/@kanmitowolabi
status
ok
fetched_at
2026-06-25 07:00:49