加密解密基础问题:字节数组和16进制字符串的相互转换

时间:2022-01-09 10:45:36

1.String 到 byte[] 的转换很简单,因为String类有直接的函数

2. byte[] 到String不能使用 new String(byte) 或 new String(byte, charset)

因为加密的过程是任意对byte[]进行运算的。所以你用任何一种编码方案来解码,得到的都会是乱码

     /**
* Constructs a new {
@code String} by decoding the specified array of bytes
* using the platform's default charset. The length of the new {
@code
* String} is a function of the charset, and hence may not be equal to the
* length of the byte array.
*
* <p> The behavior of this constructor when the given bytes are not valid
* in the default charset is unspecified. The {
@link
* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decoding process is required.
*/
public String(byte bytes[]) {
this(bytes, 0, bytes.length);
}

 

一、为什么要将加密得到的 byte[] 转换到 String ?

 

二、如何实现byte[] 转换到 String

public class HexUtil {
private static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};

public static String encodeToString(byte[] bytes) {
char[] encodedChars = encode(bytes);
return new String(encodedChars);
}

public static char[] encode(byte[] data) {
int size = data.length;
//初始化一个 char[] 数组,其数组的大小是 byte[] 参数大小的两倍。因为java是char是16位,byte是8位
char[] res = new char[size << 1];
for (int i = 0, j = 0; i < size; i++) {
System.out.println(data[i]
+ "十六进制:" + ((0xF0 & data[i]) >>> 4) + " " + (0x0F & data[i]));
//去除了低4位上的值(其实这一步是多余的),然后右移4位,得到高4位
res[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
//去除了高4位上的值,得到了低4位
res[j++] = DIGITS[0x0F & data[i]];
}
return res;
}

public static void main(String[] args){
System.out.println( encodeToString(
"127".getBytes()));
System.out.println( encodeToString(
"a".getBytes()));
System.out.println( encodeToString(
"你好".getBytes()));
}
}
/**
49十六进制:3 1
50十六进制:3 2
55十六进制:3 7
313237
97十六进制:6 1
61
-28十六进制:14 4
-67十六进制:11 13
-96十六进制:10 0
-27十六进制:14 5
-91十六进制:10 5
-67十六进制:11 13
e4bda0e5a5bd

*
*/