何时使用:加密后通常配合Base64进行编码
Base64编码 – 在线工具
Base64
java8 Base64
package com.example.demo.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.IOException;
/**
* @description: Base64编码
* @create: 2020/05/14 21:34
**/
public class EncryptBase64AndDecryptBase64 {
/** 字符编码. */
private static final String CHARSET = "UTF-8";
public static void main(String[] args) throws Exception{
byte[] encryptAES = "你好".getBytes(CHARSET);
String encryptBase64 = encryptBase64(encryptAES);
System.out.println("encryptBase64 = " + encryptBase64);
byte[] decryptBase64 = decryptBase64(encryptBase64);
System.out.println(new String(decryptBase64));
}
/**
* BASE64 加密
*
* @param cleartext 明文
* @return 密文
*/
public static String encryptBase64(byte[] cleartext) {
BASE64Encoder base64Encoder = new BASE64Encoder();
String cipherText = base64Encoder.encode(cleartext);
return cipherText;
}
/**
* BASE64 解密
*
* @param cipherText 密文
* @return 明文
*/
public static byte[] decryptBase64(String cipherText) {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);
return cipherTextBytes;
} catch (IOException e) {
e.printStackTrace();
}
// 解密错误返回 null
return null;
}
}
运行结果:
encryptBase64 = 5L2g5aW9
你好