
AES (Advanced Encryption Standard) 是一种广泛使用的对称加密算法,而GCM (Galois/Counter Mode) 是一种认证加密模式,它在提供数据机密性的同时,也提供了数据完整性和认证功能。AES/GCM/128 表示使用128位的AES密钥,工作在GCM模式下。在跨语言实现加解密时,确保所有参数(如密钥、初始化向量IV、认证标签Tag、密文、填充模式等)在不同语言之间保持一致至关重要。
AES/GCM模式的主要组成部分包括:
提供的PHP代码展示了如何使用openssl_encrypt函数进行AES-128-GCM加密。
<?php
function aes_gcm_encrypt($data, $secret) {
$cipher = 'aes-128-gcm';
$string = is_array($data) ? json_encode($data) : $data;
// 1. 密钥处理:将十六进制字符串转换为二进制
$skey = hex2bin($secret);
// 2. IV生成:生成12字节的随机IV
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$tag = NULL;
// 3. 加密操作:生成密文和认证标签
$content = openssl_encrypt($string, $cipher, $skey, OPENSSL_RAW_DATA, $iv, $tag);
// 4. 数据拼接与编码:IV、密文、标签按顺序拼接,进行hex2bin后再base64编码
$str = bin2hex($iv) . bin2hex($content) . bin2hex($tag);
return base64_encode(hex2bin($str));
}
?>从PHP代码中我们可以提取以下关键信息:
立即学习“PHP免费学习笔记(深入)”;
初始的Java解密代码在尝试解密PHP加密的内容时抛出了AEADBadTagException。这通常意味着认证标签不匹配,即解密过程中计算出的标签与接收到的标签不一致,这可能是由于密钥、IV、密文或标签本身处理不当造成的。
// 原始Java解密代码片段
private static String decrypt(String data, String mainKey, int ivLength) throws Exception {
final byte[] encryptedBytes = Base64.getDecoder().decode(data.getBytes("UTF8"));
final byte[] initializationVector = new byte[ivLength]; // 问题1:ivLength可能不正确
System.arraycopy(encryptedBytes, 0, initializationVector, 0, ivLength);
// 问题2:密钥生成方式与PHP不匹配,使用了PBKDF2
SecretKeySpec secretKeySpec = new SecretKeySpec(generateSecretKeyFromPassword(mainKey, mainKey.length()), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
// 问题3:doFinal的偏移量和长度可能未正确处理密文和标签
return new String(cipher.doFinal(encryptedBytes, ivLength, encryptedBytes.length - ivLength), "UTF8");
}
// 原始Java密钥生成函数
private static byte[] generateSecretKeyFromPassword(String password, int keyLength) throws Exception {
// ... 使用PBKDF2WithHmacSHA256,这与PHP的hex2bin完全不同
}分析发现,导致AEADBadTagException的主要原因包括:
为了实现与PHP的兼容解密,Java代码需要进行以下修正:
以下是修正后的Java解密代码:
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import javax.crypto.*;
import javax.crypto.spec.*;
public class MyTest {
public static final String ALGO = "AES";
public static final String GCM_ALGO = "AES/GCM/NoPadding";
public static final int IV_LENGTH = 12; // 明确指定IV长度为12字节
public static void main(String[] args) throws Exception {
String secret = "544553544B4559313233343536"; // PHP加密使用的十六进制密钥
String encryptStr = "Fun3yZTPcHsxBpft+jBZDe2NjGNAs8xUHY21eZswZE4iLKYdBsyER7RwVfFvuQ=="; // PHP加密后的Base64字符串
// 格式化密钥,确保其长度符合AES-128(16字节)
secret = reformatSecret(secret);
String decryptStr = decrypt(encryptStr, secret);
System.out.println("encryptString: " + encryptStr);
System.out.println("secret (formatted hex): " + secret);
System.out.println("decryptString: " + decryptStr);
}
/**
* 解密PHP加密的AES/GCM数据
* @param data Base64编码的加密字符串
* @param secret 格式化后的十六进制密钥字符串
* @return 解密后的明文字符串
* @throws Exception 加密异常
*/
private static String decrypt(String data, String secret) throws Exception {
// 1. Base64解码,得到 IV || Ciphertext || Tag 的字节数组
final byte[] encryptedBytes = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
// 2. 提取IV
final byte[] initializationVector = new byte[IV_LENGTH];
System.arraycopy(encryptedBytes, 0, initializationVector, 0, IV_LENGTH);
// 3. 将十六进制密钥字符串转换为字节数组
final byte[] keyBytes = parseHexStr2Byte(secret);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGO);
// 4. 初始化GCM参数,指定IV和认证标签长度(128位即16字节)
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
// 5. 获取Cipher实例并初始化为解密模式
Cipher cipher = Cipher.getInstance(GCM_ALGO);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
// 6. 执行解密。从IV_LENGTH偏移量开始,长度为总长度减去IV长度,这部分数据包含密文和认证标签。
// Cipher会自动根据GCMParameterSpec中的标签长度从末尾提取标签。
byte[] decryptedBytes = cipher.doFinal(encryptedBytes, IV_LENGTH, encryptedBytes.length - IV_LENGTH);
// 7. 将解密后的字节数组转换为UTF-8字符串
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
/**
* 格式化密钥:确保密钥是32个十六进制字符(16字节),不足则补零,超出则截断。
* @param secret 原始十六进制密钥字符串
* @return 格式化后的十六进制密钥字符串
*/
public static String reformatSecret(String secret) {
if (secret == null || secret.length() < 1) {
return "";
}
int secretLen = secret.length();
if (secretLen < 32) { // AES-128需要16字节密钥,即32个十六进制字符
StringBuilder str = new StringBuilder(secret);
while (secretLen < 32) {
str.append("0"); // 补零
secretLen = str.length();
}
return str.toString();
} else {
return secret.substring(0, 32); // 截断
}
}
/**
* 将十六进制字符串转换为字节数组
* @param hexStr 十六进制字符串
* @return 字节数组
*/
public static byte[] parseHexStr2Byte(String hexStr) {
int len = hexStr.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexStr.charAt(i), 16) << 4) + Character.digit(hexStr.charAt(i+1), 16));
}
return data;
}
}运行结果:
encryptString: Fun3yZTPcHsxBpft+jBZDe2NjGNAs8xUHY21eZswZE4iLKYdBsyER7RwVfFvuQ==
secret (formatted hex): 544553544B45593132333435360000000000
decryptString: Test text.{123456}在进行跨语言加密互操作时,需要特别注意以下几点:
以上就是跨语言AES/GCM/128加解密指南:PHP与Java互操作实现的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号