【发布时间】:2021-12-21 04:48:43
【问题描述】:
我正在尝试使用java来解密通过php加密的内容,但是我的java代码不能正常工作。 这是加密过程的代码。
<?php
function aes_gcm_decrypt($content, $secret) {
$cipher = 'aes-128-gcm';
$ciphertextwithiv = bin2hex(base64_decode($content));
$iv = substr($ciphertextwithiv, 0, 24);
$tag = substr($ciphertextwithiv , -32, 32);
$ciphertext = substr($ciphertextwithiv, 24, strlen($ciphertextwithiv) - 24 - 32);
$skey = hex2bin($secret);
return openssl_decrypt(hex2bin($ciphertext), $cipher, $skey, OPENSSL_RAW_DATA, hex2bin($iv), hex2bin($tag));
}
function aes_gcm_encrypt($data, $secret) {
$cipher = 'aes-128-gcm';
$string = is_array($data) ? json_encode($data) : $data;
$skey = hex2bin($secret);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$tag = NULL;
$content = openssl_encrypt($string, $cipher, $skey, OPENSSL_RAW_DATA, $iv, $tag);
$str = bin2hex($iv) . bin2hex($content) . bin2hex($tag);
return base64_encode(hex2bin($str));
}
$content = 'Test text.{123456}';
$secret = '544553544B4559313233343536';
$encryptStr = aes_gcm_encrypt($content, $secret);
print_r("encrypt -> $encryptStr \n");
print_r("\n");
$decryptStr = aes_gcm_decrypt($encryptStr, $secret);
print_r("decrypt -> $decryptStr \n");
结果:
encrypt -> Fun3yZTPcHsxBpft+jBZDe2NjGNAs8xUHY21eZswZE4iLKYdBsyER7RwVfFvuQ==
decrypt -> Test text.{123456}
然后这不是我的代码,所以我不能修改它。
这是我现在在 Java 端的代码:
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Random;
import javax.crypto.*;
import javax.crypto.spec.*;
public class MyTest {
public static void main(String[] args) throws Exception {
String secret = "544553544B4559313233343536";
String encryptStr = "Fun3yZTPcHsxBpft+jBZDe2NjGNAs8xUHY21eZswZE4iLKYdBsyER7RwVfFvuQ==";
String decryptString = decrypt(encryptStr, secret, 16);
System.out.println("decryptString: " + decryptString);
}
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];
System.arraycopy(encryptedBytes, 0, initializationVector, 0, ivLength);
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);
return new String(cipher.doFinal(encryptedBytes, ivLength, encryptedBytes.length - ivLength), "UTF8");
}
private static byte[] generateSecretKeyFromPassword(String password, int keyLength) throws Exception {
byte[] salt = new byte[keyLength];
new Random(password.hashCode()).nextBytes(salt);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
return factory.generateSecret(spec).getEncoded();
}
}
此 java 代码将抛出 AEADBadTagException。
Exception in thread "main" javax.crypto.AEADBadTagException: Tag mismatch!
at com.sun.crypto.provider.GaloisCounterMode.decryptFinal(GaloisCounterMode.java:620)
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1116)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1053)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2226)
at MyTest.decrypt(MyTest.java:24)
at MyTest.main(MyTest.java:12)
查了很多资料,还是没解决。
你们能帮我构建一个返回相同结果的 Java 代码吗?
提前致谢!!
【问题讨论】:
-
在 PHP 代码中,密钥不是由 PBKDF2 派生的,而是经过十六进制解码。因此,在 Java 代码中,除了
generateSecretKeyFromPassword(),它还必须是十六进制解码的,例如与hexStringToByteArray()。此外,PHP代码中使用的nonce大小为12字节(推荐用于GCM),即调用decrypt()时,必须将12作为第三个参数而不是16传递。 -
另外,PHP 代码使用的密钥太短。由于十六进制解码,AES-128 需要一个具有 32 个十六进制数字的字符串。目前只应用了 26 个十六进制数字,产生了 13 个字节的密钥。在 PHP 代码中使用有效的密钥。否则 PHP 将使用
0x00值填充,即在 Java 中必须显式添加此填充,在当前情况下为544553544B4559313233343536000000。 -
非常感谢您的回复!通过修改,我的代码可以正常工作。但真正的密钥是 54 个十六进制数字,产生 27 个字节的密钥,例如“544553544B4559544553544B45594B455954533132333435363738”。正如你所说,我试图将钥匙变成“544553544B4559544553544B45594B4559545331323334353637380000000000”。但这将再次引发 AEADBadTagException。我这样做有错吗?
-
通过反复阅读您的 cmets,我找到了正确的方法! “由于是十六进制解码,AES-128 需要一个 32 位十六进制数字的字符串。”。当密钥大于 32 位十六进制数字时,只需要保留前 32 位十六进制数字。谢谢 Topaco。
标签: java php encryption cryptography aes-gcm