一、
一般情况下,经过算法加密后的密文是byte类型的数组,而展示出来的加密后的就应该是字符串,这时候就应该将字符数组转换为字符串。这时候可以使用sun.misc jar包下的new BASE64Encoder().encode(byte[] b)来进行转换。相反的如果要将加密后的字符串转换为字符数组就用
sun.misc jar
包下的new BASE64Decoder().decodeBuffer(String s)来进行转换。
但是这个类是sun公司的内部方法,并没有在Java
API中公开过,不属于JDK标准库范畴,但在JDK中包含了该类,可以直接使用。但是在Eclipse和MyEclipse中直接使用,却找不到该类。
解决方案: 第一步:在使用sun.misc包下的API的项目上右键选择Build Path,选择Configure Build Path
第二步:在Java Build Path窗口,点击第三个选项卡Libraries,选择JRE System
Libraries,选择第一项Access rules,点击Edit 第三步:在弹出的窗口中点击Add
第四步:在Resolution后面选择Accessible选项,下面的Rule Pattern配置为**,点击OK即可。 第五步:点击OK
第六步:点击Apply,点击OK,就会看到工作空间会进行重新导入构建。
我们再来看导入sun.misc包下的BASE64Encoder这个类,完美解决。
参考来源(https://blog.csdn.net/weixin_42292697/article/details/107806862)
二、
我记得还有个方式Base64.encodeBase64String(byte[] b)这样将加密后的字符数组转换为字符串。这个Base64是这个包下的
org.apache.commons.codec.binary
我不知道这两种方式有什么区别,反正都能把字符数组转为字符串。
查相关资料说BASE64Encoder 和 BASE64Decoder是jdk1.8下的,jdk9已经开始移除,建议使用Base64。
参考:JDK从1.8升级到9.0.1后sun.misc.BASE64Decoder和sun.misc.BASE64Encoder不可用
package com.lipan;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
//import java.util.Base64;
import org.apache.commons.codec.binary.Base64;
/**
* @Author
* @Date
* @Description
*/
public class Niuke1 {
public static void main(String[] args) throws Exception {
test2();
}
//用BASE64Encoder方式
public static void test() throws Exception {
String str = "hello lipan";
BASE64Encoder base64Encoder = new BASE64Encoder();
// JDK1.8 BASE64Encoder 加密
String encode = base64Encoder.encode(str.getBytes());
System.out.println(encode);//bGlwYW4=
BASE64Decoder base64Decoder = new BASE64Decoder();
// JDK1.8 BASE64Decoder 解密
byte[] bytes = base64Decoder.decodeBuffer(encode);
String res = new String(bytes);
System.out.println(res);//lipan
}
//用BASE64方式
public static void test2() throws Exception {
String str = "hello lipan";
// JDK1.8 Base64加密
//String encode = Base64.getEncoder().encodeToString(str.getBytes());
String res = Base64.encodeBase64String(str.getBytes());
System.out.println(res);//aGVsbG8gbGlwYW4=
// JDK1.8 Base64解密
//byte[] bytes = Base64.getDecoder().decode(encode);
byte[] bytes = Base64.decodeBase64(res);
String ok = new String(bytes);
System.out.println(ok);//hello lipan
}
}
注意看我这个圈出来的Base64和上文中的Base64还不是出自同一个包
上文代码中的Base64出自org.apache.commons.codec.binary.Base64
这个包而下面图片中圈出的红色Base64却出自java.util.Base64
这个包,两个究竟有什么差异有待探究,要导入org.apache.commons.codec.binary.Base64这个包就需要在maven中添加如下依赖
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
三、
byte[] b = string.getBytes(StandardCharsets.UTF_8)
这里将一个字符串以utf-8的形式转换为byte数组了,StandardCharsets是下面这个包下的类
java.nio.charset.StandardCharsets
不知道为什么用这种方式指定编码方式,我记得还有一种方式就是直接用byte[] b = string.getBytes(“utf-8”)这种方式,我不清楚上面这两种方式有什么区别。