【问题标题】:How do i decrypt use AES/GCM/128 between PHP and Java我如何解密在 PHP 和 Java 之间使用 AES/GCM/128
【发布时间】: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


【解决方案1】:

我已经解决了这个问题。

这是正确的代码:

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;

    public static void main(String[] args) throws Exception {
        String secret = "544553544B4559313233343536";
        String encryptStr = "Fun3yZTPcHsxBpft+jBZDe2NjGNAs8xUHY21eZswZE4iLKYdBsyER7RwVfFvuQ==";
        secret = reformatSecret(secret);
        String decryptStr = decrypt(encryptStr, secret);
        System.out.println("encryptString: " + encryptStr);
        System.out.println("secret: " + secret);
        System.out.println("decryptString: " + decryptStr);
    }

    private static String decrypt(String data, String secret) throws Exception {
        final byte[] encryptedBytes = Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8));
        final byte[] initializationVector = new byte[IV_LENGTH];
        final byte[] key = parseHexStr2Byte(secret);
        System.arraycopy(encryptedBytes, 0, initializationVector, 0, IV_LENGTH);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, ALGO);
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
        Cipher cipher = Cipher.getInstance(GCM_ALGO);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
        return new String(cipher.doFinal(encryptedBytes, IV_LENGTH, encryptedBytes.length - IV_LENGTH), StandardCharsets.UTF_8);
    }

    public static String reformatSecret(String secret) {
        if (secret == null || secret.length() < 1) {
            return "";
        }
        int secretLen = secret.length();
        if (secretLen < 32) {
            //padding zero
            StringBuilder str = new StringBuilder(secret);
            while (secretLen < 32) {
                str.append("0");
                secretLen = str.length();
            }
            return str.toString();
        } else {
            //reserved 32 characters
            return secret.substring(0, 32);
        }
    }

    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;
    }
}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 2017-03-27
  • 2013-10-12
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 2015-02-18
相关资源
最近更新 更多