简体   繁体   English

Java Base64 Encode函数与PHP Base64 Encode函数相同吗?

[英]Java Base64 Encode function the same as PHP Base64 Encode function?

I'm trying to test a Soap Security header in PHP with values supplied by the client. 我正在尝试使用客户端提供的值在PHP中测试Soap Security标头。

They are supplying a value like... 他们正在提供类似...的价值

wTAmCL9tmg6KNpeAQOYubw==

...and saying it's a Base64 encoded value. ...并说这是Base64编码的值。

However, when I run it through PHP's Base64 decode function... 但是,当我通过PHP的Base64解码功能运行它时...

base64_decode("wTAmCL9tmg6KNpeAQOYubw==");

it translates it as: 0& m6@ .o 它将其翻译为: 0& m6@ .o

If I decode it in Java... 如果我用Java解码...

import java.util.Base64;
import java.util.Arrays;

/**
 * hello
 */
public class hello {

    public static void main(String[] args) {
        Base64.Decoder decoder = Base64.getDecoder();
        Base64.Encoder encoder = Base64.getEncoder();
        String stringEncoded = "wTAmCL9tmg6KNpeAQOYubw==";

        System.out.println("This is a decoded value: " + decoder.decode(stringEncoded));
        System.out.println("This is a re-coded value: " + encoder.encode(decoder.decode(stringEncoded)));

    }
}

I get a decoded string like this: [B@7229724f 我得到这样的解码字符串: [B@7229724f

But then if I try to re-encode that string, I get this: [B@4c873330 但是,如果我尝试重新编码该字符串, [B@4c873330得到以下信息: [B@4c873330

What am I missing here? 我在这里想念什么?

What you are missing is that the result of decoding the Base 64 value is not intended to be printed as a String. 您所缺少的是,对Base 64值进行解码的结果并不打算打印为String。 In fact, the you see this in the output of the Java println. 实际上,您在Java println的输出中看到了这一点。 That [B@7229724f is not a string representation of the decoded bytes. [B @ 7229724f不是解码字节的字符串表示形式。 It is the way a Java byte [] prints. 这是Java字节[]的打印方式。 The [B indicates a byte array, and the remaining characters are the hexadecimal digits of the object identity. [B表示字节数组,其余字符是对象标识的十六进制数字。 (It will print differently for every byte array instance and has nothing to do with the contents of the array.) (它将为每个字节数组实例打印不同的内容,并且与数组的内容无关。)

If you want the String representation of the bytes you will need to construct a String from the bytes: 如果想要字节的字符串表示形式,则需要从字节构造一个字符串:

    System.out.println("This is a decoded value: " + new String(decoder.decode(stringEncoded), StandardCharsets.UTF_8));
    System.out.println("This is a re-coded value: " + new String(encoder.encode(decoder.decode(stringEncoded), StandardCharsets.UTF_8));

Based on this answer how about specify the encoding. 基于此答案,如何指定编码。 Recommended encoding is UTF-8. 推荐的编码为UTF-8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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