链接
视频
https://www.bilibili.com/video/BV15b411P7sM?p=7&spm_id_from=pageDriver&vd_source=3efcb41ebc2977a53fbbea093c7df1b6
参考文章
https://www.cnblogs.com/xiaoyaogege/p/6305845.html
从文章中可以得到base64工具类
4 对称加密
加密解密都是用同一把钥匙。
介绍aes/des
5 DES算法
分组加密算法
明文总长度 64
密钥总长度 64 8位是校验码,不参与加密运算。
6 DES代码实现
public class DESDemo {
@Test
public static void main(String[] args) throws Exception{
String clearText="heimajjdkl";
String originKey="12345678";
String cipherText=desEncript(clearText,originKey);
System.out.println(cipherText);
String clearText2=desDecript(cipherText,originKey);
System.out.println(clearText2);
}
private static String desDecript(String cipherText, String originKey) throws Exception{
Cipher cipher = Cipher.getInstance("DES");
Key key=getKey(originKey);
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] decode = Base64.decode(cipherText);
byte[] doFinal = cipher.doFinal(decode);
return new String(doFinal);
}
/**
* 加密运算:通过对比特位进行一些数学运算。
* @param clearText
* @param originKey
* @return
* @throws Exception
*/
private static String desEncript(String clearText,String originKey) throws Exception{
//1.获取加密算法工具类对象
Cipher cipher = Cipher.getInstance("DES");
SecretKeySpec key=getKey(originKey);
//2.对工具类对象进行初始化
//mode 加密/解密模式
//key 对原始密钥处理后的密钥
cipher.init(Cipher.ENCRYPT_MODE,key);
//3 加密工具对明文进行加密
byte[] doFinal = cipher.doFinal(clearText.getBytes());
String encode = Base64.encode(doFinal);
return encode;
}
private static SecretKeySpec getKey(String originKey){
//根据给定的字节数组构造一个密钥
byte[] buffer = new byte[8];
//获取用户提供的原始密钥字节数组
byte[] originBytes=originKey.getBytes();
for(int i=0;i<8&&i<originBytes.length;i++){
buffer[i]=originBytes[i];
}
SecretKeySpec key = new SecretKeySpec(originKey.getBytes(), "DES");
return key;
}
}
7 base64处理乱码
问题由来
问题出现在,DES加密过程。将原来的byte[]加密转换后,编码表GBK很可能找不到对应的字符,造成字节丢失。
解决方案
找一个编码表,编解码都能在码表上找到对应的内容。
因为使用base64对字节数组进行编码,任何字节都可以映射成对应的base64字符,之后能恢复到字节数组,利于加密后数据的保存和运输。
使用流程
导入base64.java工具类