0

I'm trying to use java to decrypt the content encrypted through php, but my java code does not work properly. This is the code for the encryption process.

<?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");

result:

encrypt -> Fun3yZTPcHsxBpft+jBZDe2NjGNAs8xUHY21eZswZE4iLKYdBsyER7RwVfFvuQ==

decrypt -> Test text.{123456}

And then this is not my code, so I can't modify it.

Here is the code I'm having for now on my Java side:

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

This java code will throw an 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)

I have searched a lot of information, but still can not solve.

Can you guys possibly help me with building a Java code, that returns the same results?

Thanks in advance!!

job
  • 1
  • In the PHP code the key is nowhere derived with PBKDF2, instead it is hex decoded. Consequently, in the Java code, instead of `generateSecretKeyFromPassword()`, it must also be hex decoded, e.g. with [`hexStringToByteArray()`](https://stackoverflow.com/a/140861/9014097). In addition, the nonce used in the PHP code has a size of 12 bytes (recommended for GCM), i.e. when calling `decrypt()`, 12 must be passed as 3rd parameter instead of 16. – Topaco Nov 08 '21 at 11:13
  • Also, the PHP code uses a key that is too short. Because of the hex decoding, a string with 32 hex digits is needed for AES-128. Currently only 26 hex digits are applied, resulting in a 13 bytes key. Use a valid key in the PHP code. Otherwise PHP will pad with `0x00` values, i.e. in Java this padding has to be added explicitly, `544553544B4559313233343536000000` in the current case. – Topaco Nov 08 '21 at 11:15
  • Thank you very much for this reply! With the modification, my code is working properly. but the real key are 54 hex digits, resulting in a 27 bytes key, e.g. "544553544B4559544553544B45594B455954533132333435363738" . I tried to turn the key into "544553544B4559544553544B45594B4559545331323334353637380000000000" as you said. But this will throw an AEADBadTagException again. Is it wrong for me to do this? – job Nov 08 '21 at 12:30
  • By reading your comments over and over, I found the right way! "Because of the hex decoding, a string with 32 hex digits is needed for AES-128.".When the key is greater than 32 hex digits, only the first 32 hex digits need to be kept.Thank you Topaco. – job Nov 08 '21 at 12:52

1 Answers1

0

I have solved this problem.

This is the correct code:

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;
    }
}
job
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 09 '21 at 07:07