Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tariqbilal's avatar

Converting Java to PHP

I am communicating with a java api, where I need to generate exact AES key as generated on Java.

Issue is AES encryption is treated differently in Java and PHP as for the bytes and string conversion.

Here is the code. Any help would be great.

// 2nd File

// AES File

 

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

import java.util.Base64;

 

import javax.crypto.Cipher;

import javax.crypto.spec.SecretKeySpec;

 

public class AES {

 

  private static SecretKeySpec secretKey;

  private static byte[] key;

 

  public static void setKey(final String myKey) {

    MessageDigest sha = null;

    try {

      key = myKey.getBytes("UTF-8");

      sha = MessageDigest.getInstance("SHA-1");

      key = sha.digest(key);

      key = Arrays.copyOf(key, 16);

      secretKey = new SecretKeySpec(key, "AES");

    } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {

      e.printStackTrace();

    }

  }

 

  public static String encrypt(final String strToEncrypt, final String secret) {

    try {

      setKey(secret);

      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

      cipher.init(Cipher.ENCRYPT_MODE, secretKey);

      byte[] enc = cipher.doFinal(strToEncrypt.getBytes("UTF-8"));

      String encEncode = Base64.getEncoder()

                        .encodeToString(enc);

      return encEncode;

    } catch (Exception e) {

      System.out.println("Error while encrypting: " + e.toString());

    }

    return null;

  }

 

  public static String decrypt(final String strToDecrypt, final String secret) {

    try {

      setKey(secret);

      Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

      cipher.init(Cipher.DECRYPT_MODE, secretKey);

      return new String(cipher.doFinal(Base64.getDecoder()

        .decode(strToDecrypt)));

    } catch (Exception e) {

      System.out.println("Error while decrypting: " + e.toString());

    }

    return null;

  }

}
0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Which part are you stuck on? Maybe ask chat gpt to convert it for you?

jlrdw's avatar

You don't just convert, you rewrite using PHP.

Please or to participate in this conversation.