mqtt 变为乱码 接受16进制字节流_加密解密基础问题:字节数组和(16进制)字符串的相互转换...

本文介绍了在加密解密过程中,如何进行String到byte[]以及byte[]到String的转换。由于加密后的byte[]通常无法通过特定字符编码还原,因此通常使用16进制转换方法将byte[]转为String存储。转换过程包括使用16进制字符表示每个字节的高4位和低4位,以便进行存储和比较。此外,还提供了反向转换的实现,即从16进制字符串恢复原始byte[]。
摘要由CSDN通过智能技术生成

在加密时,一般加密算法和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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值