一、Base64加密
因为Java 8的java.util套件中,新增了Base64的类别,可以用来处理Base64的编码与解码。所以这里需要区分下jdk版本
1、jdk8之前,
(1)使用com.sun.org.apache.xerces.internal.impl.dv.util.Base64
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class encode {
public static void main(String[] args) throws Exception{
//第一种
Base64 base64 = new Base64();
String code = "需要加密的文字";
byte[] byData = code.getBytes("UTF-8");
String codeEn = base64.encode(byData);
System.out.println("加密后:"+codeEn);
String codeDe = new String (base64.decode(codeEn),"UTF-8");
System.out.println("解密后:"+codeDe);
/**补充:可使用 import org.apache.commons.codec.binary.Base64;
* Base64().encodeToString(encrypted)
*/
}
}
(2)使用自己的Base64工具类
package com.jsyl.stfw.utils;
/**
* Author: Pagegle李义根
* Date: 2019/12/3 16:59
* Content:
*/
public class Base64
{
/**
* Base64编码表�??
*/
private static final char[] BASE64CODE = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '+', '/',};
/**
* Base64解码表�??
*/
private static final byte[] BASE64DECODE = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, // 注意两个63,为兼容SMP�?
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 63, -1,
63, // �?/”和�?-”都翻译�?63�?
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, // 注意两个0�?
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1,
-1, // “A”和�?=”都翻译�?0�?
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1,
-1, -1, -1, -1,};
private static final int HEX_255 = 0x0000ff;
private static final int HEX_16515072 = 0xfc0000;
private static final int HEX_258048 = 0x3f000;
private static final int HEX_4032 = 0xfc0;
private static final int HEX_63 = 0x3f;
private static final int HEX_16711680 = 0xff0000;
private static final int HEX_65280 = 0x00ff00;
private static final int NUMBER_TWO = 2;
private static final int NUMBER_THREE = 3;
private static final int NUMBER_FOUR = 4;
private static final int NUMBER_SIX = 6;
private static final int NUMBER_EIGHT = 8;
private static final int NUMBER_TWELVE = 12;
private static final int NUMBER_SIXTEEN = 16;
private static final int NUMBER_EIGHTEEN = 18;
/**
* 构�?�方法私有化,防止实例化�?
*/
public Base64()
{ }
/**
* Base64编码。将字节数组中字�?3个一组编码成4个可见字符�??
*
* @param b �?要被编码的字节数据�??
* @return 编码后的Base64字符串�??
*/
public String encode(byte[] b)
{
int code = 0;
// 按实际编码后长度开辟内存,加快速度
StringBuffer sb = new StringBuffer(((b.length - 1) / NUMBER_THREE) << NUMBER_TWO + NUMBER_FOUR);
// 进行编码
for (int i = 0; i < b.length; i++)
{
code |=
(b[i] << (NUMBER_SIXTEEN - i % NUMBER_THREE * NUMBER_EIGHT))
& (HEX_255 << (NUMBER_SIXTEEN - i % NUMBER_THREE * NUMBER_EIGHT));
if (i % NUMBER_THREE == NUMBER_TWO || i == b.length - 1)
{
sb.append(BASE64CODE[(code & HEX_16515072) >>> NUMBER_EIGHTEEN]);
sb.append(BASE64CODE[(code & HEX_258048) >>> NUMBER_TWELVE]);
sb.append(BASE64CODE[(code & HEX_4032) >>> NUMBER_SIX]);
sb.append(BASE64CODE[code & HEX_63]);
code = 0;
}
}
// 对于长度�?3的整数�?�的字节数组,编码前先补0,编码后结尾处编码用=代替�?
// =的个数和短缺的长度一致,以此来标识出数据实际长度
if (b.length % NUMBER_THREE > 0)
{
sb.setCharAt(sb.length() - 1, '=');
}
if (b.length % NUMBER_THREE == 1)
{
sb.setCharAt(sb.length() - NUMBER_TWO, '=');
}
return sb.toString();
}
/**
* Base64解码�?
*
* @param code 用Base64编码的ASCII字符�?
* @return 解码后的字节数据
*/
public static byte[] decode(String code)
{
// �?查参数合法�??
if (code == null)
{
return null;
}
int len = code.length();
if (len % NUMBER_FOUR != 0)
{
throw new IllegalArgumentException("Base64 string length must be 4*n");
}
if (code.length() == 0)
{
return new byte[0];
}
// 统计填充的等号个�?
int pad = 0;
if (code.charAt(len - 1) == '=')
{
pad++;
}
if (code.charAt(len - NUMBER_TWO) == '=')
{
pad++;
}
// 根据填充等号的个数来计算实际数据长度
int retLen = len / NUMBER_FOUR * NUMBER_THREE - pad;
// 分配字节数组空间
byte[] ret = new byte[retLen];
// 查表解码
char ch1, ch2, ch3, ch4;
int i;
for (i = 0; i < len; i += NUMBER_FOUR)
{
int j = i / NUMBER_FOUR * NUMBER_THREE;
ch1 = code.charAt(i);
ch2 = code.charAt(i + 1);
ch3 = code.charAt(i + NUMBER_TWO);
ch4 = code.charAt(i + NUMBER_THREE);
int tmp =
(BASE64DECODE[ch1] << NUMBER_EIGHTEEN) | (BASE64DECODE[ch2] << NUMBER_TWELVE)
| (BASE64DECODE[ch3] << NUMBER_SIX) | (BASE64DECODE[ch4]);
ret[j] = (byte)((tmp & HEX_16711680) >> NUMBER_SIXTEEN);
if (i < len - NUMBER_FOUR)
{
ret[j + 1] = (byte)((tmp & HEX_65280) >> NUMBER_EIGHT);
ret[j + NUMBER_TWO] = (byte)((tmp & HEX_255));
}
else
{
if (j + 1 < retLen)
{
ret[j + 1] = (byte)((tmp & HEX_65280) >> NUMBER_EIGHT);
}
if (j + NUMBER_TWO < retLen)
{
ret[j + NUMBER_TWO] = (byte)((tmp & HEX_255));
}
}
}
return ret;
}
}
2、jdk8,使用java.util.Base64
import java.util.Base64;
public class encode {
public static void main(String[] args) throws Exception{
//第二种
Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();
String code = "需要加密的文字";
byte[] byData = code.getBytes("UTF-8");
String codeEn = encoder.encodeToString(byData);
System.out.println("加密后:"+codeEn);
String codeDe = new String(decoder.decode(codeEn),"UTF-8");
System.out.println("解密后:"+codeDe);
}
}
比较:Java 8提供的Base64拥有更好的效能。实际测试编码与解码速度要比sun.mis c套件提供的还要快至少11倍,比Apache Commons Codec提供的还要快至少3倍。
二、AES加密
AES有五种加密模式:1.电码本模式(Electronic Codebook Book (ECB));2.密码分组链接模式(Cipher Block Chaining (CBC));3.计算器模式(Counter (CTR));4.密码反馈模式(Cipher FeedBack (CFB));5.输出反馈模式(Output FeedBack (OFB))
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* Author: Pagegle李义根
* Date: 2019/12/4 10:21
* Content:
*/
public class AESUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);
private static final String KEY_ALGORITHM = "AES";
private static final String CHAR_SET = "UTF-8";
private static final String PWD = "Pagegle";
/**
* AES的密钥长度
*/
private static final Integer SECRET_KEY_LENGTH = 128;
/**
* 加解密算法/工作模式/填充方式
*/
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* AES加密操作
*
* @param content 待加密内容
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content) {
if (StringUtils.isAnyEmpty(content)) {
LOGGER.error("AES encryption params is null");
return null;
}
try {
//创建密码器
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
byte[] byteContent = content.getBytes(CHAR_SET);
//初始化为加密密码器
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(PWD));
byte[] encryptByte = cipher.doFinal(byteContent);
return Base64.encodeBase64String(encryptByte);
} catch (Exception e) {
LOGGER.error("AES encryption operation has exception,content:{},password:{}", content, PWD, e);
}
return null;
}
/**
* AES解密操作
*
* @param encryptContent 加密的密文
* @return
*/
public static String decrypt(String encryptContent) {
if (StringUtils.isAnyEmpty(encryptContent)) {
LOGGER.error("AES decryption params is null");
return null;
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(PWD));
//执行解密操作
byte[] result = cipher.doFinal(Base64.decodeBase64(encryptContent));
return new String(result, CHAR_SET);
} catch (Exception e) {
LOGGER.error("AES decryption operation has exception,content:{},password:{}", encryptContent, PWD, e);
}
return null;
}
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
//生成指定算法密钥的生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
keyGenerator.init(SECRET_KEY_LENGTH, new SecureRandom(password.getBytes()));
//生成密钥
SecretKey secretKey = keyGenerator.generateKey();
//转换成AES的密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
}
AES加密在 windows 操作系统下加解密正常,但部署到 linux 环境中相同的输入加密结果不正确,并且每次运行返回的结果都不同。
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
//生成指定算法密钥的生成器
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
//只适用windows
// keyGenerator.init(SECRET_KEY_LENGTH, new SecureRandom(password.getBytes()));
//指定强随机数的生成方式
//兼容linux
SecureRandom random = SecureRandom. getInstance("SHA1PRNG");
random. setSeed(password. getBytes(CHAR_SET));
keyGenerator. init(SECRET_KEY_LENGTH,random);// 只能是128位
//生成密钥
SecretKey secretKey = keyGenerator.generateKey();
//转换成AES的密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}