How to Implement AES Encryption in Java and PHP: Code, Comparison, and Tips
This guide explains the fundamentals of AES symmetric encryption, compares Java and PHP implementations, highlights their shared features and differences, provides complete code samples for encryption and decryption, and offers practical advice on key management, IV usage, and performance considerations.
Overview
AES (Advanced Encryption Standard) is a symmetric block cipher that supports 128‑, 192‑, and 256‑bit keys. The following sections show how to encrypt and decrypt data with AES in Java (using javax.crypto) and PHP (using the openssl extension), and compare the two implementations.
Similarities
Symmetric encryption : Both languages use the same secret key for encryption and decryption.
Key lengths : 128‑bit, 192‑bit and 256‑bit keys are supported.
Encryption modes : Common modes such as ECB and CBC are available in both environments.
Differences
Libraries / extensions : Java relies on the javax.crypto package; PHP uses the openssl extension.
API style : Java works with Cipher and SecretKeySpec objects; PHP calls openssl_encrypt and openssl_decrypt directly.
Performance : Java is compiled and may be faster for large workloads, while PHP is interpreted; actual speed depends on the use case.
Java Implementation
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class EncryptionUtil {
private static final String ALGORITHM = "AES";
// 16‑byte key for AES‑128
private static final String KEY = "TinywanNtiT13N0S";
public static String encrypt(String plainText) throws Exception {
SecretKeySpec spec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, spec);
byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(String cipherText) throws Exception {
SecretKeySpec spec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, spec);
byte[] decoded = Base64.getDecoder().decode(cipherText);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted, StandardCharsets.UTF_8);
}
}
public class Main {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"开源技术小栈\",\"id\":\"Tinywan\"}";
String enc = EncryptionUtil.encrypt(json);
System.out.println("Encrypted: " + enc);
String dec = EncryptionUtil.decrypt(enc);
System.out.println("Decrypted: " + dec);
}
}PHP Implementation
<?php
declare(strict_types=1);
class Encryption {
public const AES_128_ECB = 'AES-128-ECB';
public const AES_192_ECB = 'AES-192-ECB';
public const AES_256_ECB = 'AES-256-ECB';
public static function encrypt(string $data, string $key, string $algo = self::AES_128_ECB): string {
$encrypted = openssl_encrypt($data, $algo, $key, OPENSSL_RAW_DATA);
return base64_encode($encrypted);
}
public static function decrypt(string $data, string $key, string $algo = self::AES_128_ECB): string {
return openssl_decrypt(base64_decode($data), $algo, $key, OPENSSL_RAW_DATA);
}
}
?>Important Considerations
Key management : Store keys securely (e.g., environment variables, secret vaults). Never hard‑code them in source code.
Initialization Vector (IV) : Required for modes such as CBC. Generate a random IV for each encryption operation and transmit it alongside the ciphertext (e.g., prepend it).
Key length ↔ algorithm mapping :
16‑byte key → AES-128-ECB (or AES-128-CBC)
24‑byte key → AES-192-ECB 32‑byte key →
AES-256-ECBExample Demonstrations
AES‑128‑ECB (16‑byte key)
Key: TinywanNtiT13N0S Java encryption output (Base64 ciphertext):
GlOoKJFve8Z6kTcSAN+wvYV9zQbgjZZEFOzKbMPJqzAZlSQXwyWKtSFNtUAyRIfsPHP decryption using the same key reproduces the original JSON.
AES‑192‑ECB (24‑byte key)
Key: Tinywan20240502NtiT13N0S Java encryption output:
T4I/+kI1HflevpVXniCS3hI3B2PAMKuuWLK/GS6lBn8571l6cmiZzAPUQq2cjyxPcak3gSOZQiTEn3ca6RaYRg==PHP decryption with the same key and algorithm restores the original payload.
AES‑256‑ECB (32‑byte key)
Key: Tinywan20240502NtiT13N0SHaoBoWan Java encryption output:
PxbJbuvOzodPJJhTXqOkN96kYu8ut07TipLRk4tmytOng1tB4mPEwq1DwvTDeH1VI7Ipe01m/lAd/0HIHx1npg==PHP decryption with the matching key and algorithm yields the original JSON.
Conclusion
Both Java and PHP can perform AES encryption and decryption correctly; the cryptographic principles are identical while the APIs differ. Choose the language that fits the project, manage keys and IVs securely, and avoid exposing secret material in source code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
