简体   繁体   中英

Sending ByteArray from PHP to Java

I have problems with sending AES encrypted data from JAVA to PHP.

My encrypt function:

public static byte[] encrypt(String input, String key, String iv) {

    byte[] raw = key.getBytes(Charset.forName("UTF8"));
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    try {
        Cipher cipher = Cipher.getInstance(CIPHER_MODE);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(iv.getBytes()));
        return cipher.doFinal(padString(input).getBytes("UTF-8"));
    } catch (Exception e) {
    }

    return new byte[0];
}

encrypt function is returning data in byte array To send POST data, I'm using apache HttpClient/HttpPost (preferred, but not necessary)

    HttpEntity params = MultipartEntityBuilder.create()
            .addTextBody("data1", new String(encodedData1, Charset.forName("UTF8")))
            .addTextBody("data2", new String((encodedData2, Charset.forName("UTF8")))
            .addTextBody("data3", "data3").build();

Now, I recieve data with PHP server (i can't add functionality here)

        $data1 = filter_input(INPUT_POST, 'data1');
        $data2 = filter_input(INPUT_POST, 'data2');
        $data1decoded = DecryptAES($data1, $key, $iv);
        $data2decoded = DecryptAES($data2, $key, $iv);

What is a proper way to send encoded byte[] from JAVA to PHP? I know, that Base64.encode would be probably best option, but unfortunately (as I have mentioned earlier) I can't modify PHP server-side code... new String(encodedData1, Charset.forName("UTF8")) is not working.

In node.js I can use toString('binary') to send data in proper format.

You can't just create new String (Java is too fancy for that).

Use

public static String byteToString(byte[] bytes) {
    StringBuilder b = new StringBuilder();
    for (byte c : bytes) {
        b.append((char) (c >= 0 ? c : 256 + c));
    }
    return b.toString();
}

Using your example

HttpEntity params = MultipartEntityBuilder.create()
          .addTextBody("data", byteToString(data))
          .build();

Instead of

new String(encodedData1, Charset.forName("UTF8"))

you should use

new String(encodedData1)

Your byte array doesn't contain an UTF8 text anymore once it has been encrypted. You would preserve the exact structure of your byte aray by sending it in its original form with the addBinaryBody method instead of casting it to a String in order to use the addTextBody method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM