gpt4 book ai didi

java - Java 中字节的编码/解码是如何工作的?

转载 作者:行者123 更新时间:2023-11-30 02:49:46 25 4
gpt4 key购买 nike

小背景:我正在做 Cryptopals 挑战,我完成了 https://cryptopals.com/sets/1/challenges/1但意识到我没有学到我认为应该学习(或编码)的东西。

我正在使用 Apache Commons Codec 库进行 Hex 和 Base64 编码/解码。目标是解码十六进制字符串并将其重新编码为 Base64。页面底部的“提示”显示 “始终对原始字节进行操作,而不是对编码字符串进行操作。仅使用十六进制和 base64 进行 pretty-print 。”

这是我的答案...

private static Hex forHex = new Hex();
private static Base64 forBase64 = new Base64();

public static byte[] hexDecode(String hex) throws DecoderException {
byte[] rawBytes = forHex.decode(hex.getBytes());
return rawBytes;
}
public static byte[] encodeB64(byte[] bytes) {
byte[] base64Bytes = forBase64.encode(bytes);
return base64Bytes;
}

public static void main(String[] args) throws DecoderException {

String hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";


//decode hex String to byte[]
byte[] myHexDecoded = hexDecode(hex);
String myHexDecodedString = new String(myHexDecoded);

//Lyrics from Queen's "Under Pressure"
System.out.println(myHexDecodedString);

//encode myHexDecoded to Base64 encoded byte[]
byte[] myHexEncoded = encodeB64(myHexDecoded);
String myB64String = new String(myHexEncoded);

//"pretty printing" of base64
System.out.println(myB64String);

}

...但我觉得我作弊了。我没有学习如何解码以十六进制编码的字节,也没有学习如何将“纯”字节编码为 Base64,我只是学习了如何使用库为我做一些事情。

如果我要在 Java 中获取一个字符串,然后获取它的字节,我将如何将这些字节编码为十六进制?例如,以下代码片段将“Hello”(可读的英语)转换为每个字符的字节值:

String s = "Hello";
char[] sChar = s.toCharArray();
byte[] sByte = new byte[sChar.length]
for(int i = 0; i < sChar.length; i++) {
sByte[i] = (byte) sChar[i];
System.out.println("sByte[" + i + "] = " +sByte[i]);
}

得出 sByte[0] = 72、sByte[1] = 101、sByte[2] = 108、sByte[3] = 108、sByte[4] = 111

让我们以“o”为例 - 我猜测它的十进制版本是 111 - 我是否只需采用其十进制版本并将其更改为十六进制版本?

如果是这样,要解码,我是否只需一次取出十六进制字符串 2 中的字符,将它们分解为十进制值,然后转换为 ASCII?它总是 ASCII 吗?

最佳答案

to decode, do I just take the the characters in the hex String 2 at a time, decompose them to decimal values, then convert to ASCII? Will it always be ASCII?

没有。您一次获取字符 2,将字符“0”转换为数值 0,将字符“1”转换为数值 1,...,将字符“a”(或“A”,具体取决于哪个)您想要支持的编码)为数值 10,...,字符 'f' 或 'F' 为数值 15。

然后将第一个数值乘以 16,并将其添加到第二个数值以获取字节的无符号整数值。然后将该无符号整数值转换为有符号字节。

ASCII 与该算法无关。

要了解它在实践中是如何完成的,由于 commons-codec 是开源的,您只需查看它的实现即可。

关于java - Java 中字节的编码/解码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com