不多讲,直接上代码,项目上正在使用的,自己封装的工具类
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import org.apache.commons.codec.binary.Base64;
/**
* <p>
* DesUtils.java 数据加密
* </p>
*
* @since 2019年2月14日 上午9:11:25
* @author XinLau
* @version 1.0
*/
public class DesUtils {
/**
* KEY
*/
private static Key KEY;
/**
* 秘钥key
*/
private static String KEY_STR = "unXuiIsNtLvAzU@#1996";
/**
* 算法
*/
private static String ALGORITHM = "DES";
/**
* 编码格式
*/
private static String CHARSETNAME = "UTF-8";
/**
* 加密次数解密次数
*/
private static int DEGREE = 1;
static {
try {
// 生成算法对象
KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
// 使用安全策略
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
// 设置秘钥种子
secureRandom.setSeed(KEY_STR.getBytes());
// 初始化算法对象
generator.init(secureRandom);
// 生成秘钥对象
KEY = generator.generateKey();
generator = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <p>
* getEncryptString 对字符串进行加密,返回BASE64的加密字符串
* </p>
*
* @param str
* @return String
* @author XinLau
* @since 2019年2月14日上午10:18:58
*/
private static String getEncryptString(String str) {
// 基于base64编码加密,byte[]转成encode好的String
org.apache.commons.codec.binary.Base64 base64Decoder = new org.apache.commons.codec.binary.Base64();
try {
// 设置编码格式
byte[] strBytes = str.getBytes(CHARSETNAME);
// 获取加密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化密码信息
cipher.init(Cipher.ENCRYPT_MODE, KEY);
// 加密
byte[] encryptStrBytes = cipher.doFinal(strBytes);
// 返回加密之后的信息
return base64Decoder.encodeToString(encryptStrBytes);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <p>
* getDecryptString 对BASE64加密字符串进行解密
* </p>
*
* @param str
* @return String
* @author XinLau
* @since 2019年2月14日上午10:39:56
*/
private static String getDecryptString(String str) {
// 基于base64编码,接受byte[]并转成String
try {
// 将字符串docode成byte[]
byte[] strBytes = Base64.decodeBase64(str);
// 获取解密对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 初始化解密信息
cipher.init(Cipher.DECRYPT_MODE, KEY);
// 解密
byte[] decodeStrBytes = cipher.doFinal(strBytes);
// 返回解密之后的信息
return new String(decodeStrBytes, CHARSETNAME);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* <p>
* doEncrypt 执行加密
* </p>
*
* @param str 要加密的字符串
* @param degree 加密程度(加密次数)
* @return String
* @author XinLau
* @since 2019年2月14日上午10:42:44
*/
public String doEncrypt(String str, int degree) {
DEGREE = degree;
for (int i = 0; i < DEGREE; i++) {
str = getEncryptString(str);
}
return str;
}
/**
* <p>
* doDecrypt 执行解密
* </p>
*
* @param str 要解密的字符串
* @param degree 解密程度(加密次数)
* @return String
* @author XinLau
* @since 2019年2月14日上午10:44:02
*/
public String doDecrypt(String str, int degree) {
DEGREE = degree;
for (int i = 0; i < DEGREE; i++) {
str = getDecryptString(str);
}
return str;
}
}