我想将字符串转换为十六进制,然后再转换为字节数组。到目前为止,这是我的代码:
public static void findKey(){
Cipher cipher;
SecretKeySpec key;
byte [] keyBytes;
byte [] pt;
byte [] ct;
String plaintext = "Plaintxt";
ct = new byte [] {(byte)0x4A, (byte)0xC4, (byte)0x55, (byte)0x3D, (byte)0xB3, (byte)0x37, (byte)0xCA, (byte)0xB3};
String ptHex = asciiToHex(plaintext);
System.out.println(ptHex);
pt = ptHex.getBytes();
printByteArray(pt);
}
我转换为十六进制的方法工作正常,但是当我使用 getBytes
时,它显然将它转换为 16 字节,这不是我想要的。那只是一次尝试。这是仅打印我的字符串以确保它有效然后打印不正确的字节数组的输出:
506c61696e747874
[ 35 30 36 63 36 31 36 39 36 65 37 34 37 38 37 34 ]
-------------Key Found-------------
我想将 50、6c、61 等放入字节数组中,就像我为 ct 所做的那样,如 0x50、0x6c 等。
这可能吗?
最佳答案
尝试
byte[] getBytes(String s) {
byte[] a = new byte[s.length() / 2];
for (int i = 0; i < a.length; i++) {
a[i] = Byte.parseByte(s.substring(i * 2, i * 2 + 2), 16);
}
return a;
}
关于java - 如何将十六进制字符串直接转换为字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14794708/