在加密时,一般加密算法和hash算法,它们操作的都是字节数组,对字节数组按照加密算法进行各种变换,运算,得到的结果也是字节数组。而我们一般是要求对字符串进行加密,所以就涉及到字符串String到 byte[] 的转换,这个很简单。同时在解密时,也涉及到字节数组byte[] 到 String 的转换。另外在对用户的密码进行hash加密之后,最终是要保存在数据库中,所以加密得到 byte[] 也要转换到 String.
1. String 到 byte[] 的转换很简单,因为String类有直接的函数:
public byte[] getBytes(Charset charset) {if (charset == null) throw newNullPointerException();return StringCoding.encode(charset, value, 0, value.length);
}/*** Encodes this {@codeString} into a sequence of bytes using the
* platform's default charset, storing the result into a new byte array.*
*@returnThe resultant byte array
*
*@sinceJDK1.1*/
public byte[] getBytes() {return StringCoding.encode(value, 0, value.length);
}
2.但是,byte[] 到String 的转换却没有那么简单
其原因是,我们不能简单的使用使用String的函数:
/*** Constructs a new {@codeString} 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.
*
*
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(bytebytes[]) {this(bytes, 0, bytes.length);
}/*** Constructs a new {@codeString} by decoding the specified array of
* bytes using the specified {@linkplainjava.nio.charset.Charset charset}.
* The length of the new {@codeString} is a function of the charset, and
* hence may not be equal to the length of the byte array.
*
*
This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. The {@link* java.nio.charset.CharsetDecoder} class should be used when more control
* over the decodi