繁体   English   中英

Base 64解码byte []转换为字符串

[英]Base 64 decoding byte[] casted into a string

我得到了一些编码后的日志信息,将其转换为字符串以进行传输(转换可能很难看,但是可以正常工作)。

我正在尝试将其转换回byte []以便对其进行解码,但是它不起作用:

byte[] encodedBytes = android.util.Base64.encode((login + ":" + password).getBytes(), NO_WRAP);
String encoded = "Authentification " + encodedBytes;

String to_decode = encoded.substring(17);
byte[] cast1 = to_decode;            // error
byte[] cast2 = (byte[]) to_decode;   // error
byte[] cast3 = to_decode.getBytes();
// no error, but i get something totally different from encodedBytes (the array is even half the size of encodedBytes)
// and when i decode it i got an IllegalArgumentException

这3个演员表不起作用,有什么主意吗?

这里有多个问题。

通常,您需要使用Base64.decode来反转Base64.encode的结果:

byte[] data = android.util.Base64.decode(to_decode, DEFAULT);

通常,您应该总是问自己“我如何执行从X型到Y型的转换?” 在研究如何从Y型返回X型时。

请注意,您的代码中也有错别字-“身份验证”应为“身份验证”。

但是,您的编码遇到了问题-您正在创建一个byte[] ,并使用字符串串联将在字节数组上调用toString() ,这不是您想要的。 您应该改为调用encodeToString 这是一个完整的示例:

String prefix = "Authentication "; // Note fix here...
// TODO: Don't use basic authentication; it's horribly insecure.
// Note the explicit use of ASCII here and later, to avoid any ambiguity.
byte[] rawData = (login + ":" + password).getBytes(StandardCharsets.US_ASCII);
String header = prefix + Base64.encodeToString(rawData, NO_WRAP);

// Now to validate...
String toDecode = header.substring(prefix.length());
byte[] decodedData = Base64.decode(toDecode, DEFAULT);
System.out.println(new String(decodedData, StandardCharsets.US_ASCII));

暂无
暂无

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

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