目录
一、加密--解密
1.Base64
jdk1.7:
String str="张三";
BASE64Encoder encoder = new BASE64Encoder();
//加密
String encode=encoder.encode(str.getBytes());
//解密
String decode=new String(decoder.decodeBuffer(str))
jdk1.8:
package com.test.utils;
import org.apache.tomcat.util.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
/**
* @Author:
* @CreateTime: 2023-08-03 16:27
* @Description: Base64加密解密工具类
*/
public class Base64Utils {
/**
* 字符编码
*/
public final static String ENCODING = "UTF-8";
/**
* @description: Base64编码
* @author:
* @date: 2023/8/3 16:31
* @param: [data] 待编码数据
* @return: java.lang.String 编码数据
**/
public static String encode(String data) {
try {
byte[] b = Base64.encodeBase64(data.getBytes(ENCODING));
return new String(b, ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* @description: Base64安全编码 遵循RFC 2045实现
* @author:
* @date: 2023/8/3 16:33
* @param: [data] 待编码数据
* @return: java.lang.String 编码数据
**/
public static String encodeSafe(String data) {
try {
byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true);
return new String(b, ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* @description: Base64解码
* @author: zhangqingyun
* @date: 2023/8/3 16:35
* @param: [data] 待解码数据
* @return: java.lang.String 解码数据
**/
public static String decode(String data) {
try {
byte[] b = Base64.decodeBase64(data.getBytes(ENCODING));
return new String(b, ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
2.AES
package com.test.utils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* @Author:
* @CreateTime: 2023-08-03 16:50
* @Description: Aes加密解密工具类
*/
public class AesUtils {
private static final String KEY_AES = "AES";
private static final int KEY_LENGTH = 16;
private static final String KEY = "aWXoyC4UNb137965";//秘钥
/**
* @description: Aes加密
* @author:
* @date: 2022/10/18 14:15
* @param: [data] 待编码数据
* @return: java.lang.String 编码数据
**/
public static String encrypt(String data) {
try {
if (KEY == null || KEY.length() != KEY_LENGTH) {
throw new IllegalArgumentException("密钥长度必须是16位");
}
byte[] raw = KEY.getBytes();
SecretKeySpec skySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.ENCRYPT_MODE, skySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return byte2hex(encrypted);
} catch (Exception e) {
System.out.println("AES加密方法出错" + e);
}
return null;
}
/**
* @description: Aes解密
* @author:
* @date: 2022/10/18 14:16
* @param: [data] 待解码数据
* @return: java.lang.String 解码数据
**/
public static String decrypt(String data) {
try {
if (KEY == null || KEY.length() != KEY_LENGTH) {
throw new IllegalArgumentException("密钥长度必须是16位");
}
byte[] raw = KEY.getBytes();
SecretKeySpec skySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.DECRYPT_MODE, skySpec);
byte[] encrypted1 = hex2byte(data);
byte[] original = cipher.doFinal(encrypted1);
return new String(original);
} catch (Exception e) {
System.out.println("AES解密出错" + e);
}
return null;
}
/**
* @description: Aes对称加密算法---加密
* @author: zhangqingyun
* @date: 2023/8/3 17:10
* @param: [data] 待编码数据
* @return: java.lang.String 编码数据
**/
public static String encryptWithAES(String data) {
byte[] encryptedBytes = null;
try {
Cipher cipher = Cipher.getInstance(KEY_AES);
SecretKey secretKey = generateAESKey(KEY);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
e.printStackTrace();
}
return Base64.getEncoder().encodeToString(encryptedBytes);
}
/**
* @description: Aes对称加密算法---解密
* @author: zhangqingyun
* @date: 2023/8/3 17:13
* @param: [data] 待解码数据
* @return: java.lang.String 解码数据
**/
public static String decryptWithAES(String data) {
byte[] decryptedBytes = new byte[0];
try {
Cipher cipher = Cipher.getInstance(KEY_AES);
SecretKey secretKey = generateAESKey(KEY);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(data));
} catch (Exception e) {
e.printStackTrace();
}
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static byte[] hex2byte(String hex) {
if (hex == null) {
return new byte[0];
}
int l = hex.length();
int n = 2;
if (l % n == 1) {
return new byte[0];
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / n; i++) {
b[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2),
16);
}
return b;
}
public static String byte2hex(byte[] b) {
StringBuilder hs = new StringBuilder();
String tmp;
for (byte value : b) {
tmp = (Integer.toHexString(value & 0XFF));
if (tmp.length() == 1) {
hs.append("0").append(tmp);
} else {
hs.append(tmp);
}
}
return hs.toString().toUpperCase();
}
/**
* @description: 生成AES密钥
* @author:
* @date: 2023/8/3 17:05
* @param: [password] 密码
* @return: javax.crypto.SecretKey 密钥
**/
private static SecretKey generateAESKey(String password) {
byte[] keyBytes = null;
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_AES);
keyGenerator.init(128);
byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
keyBytes = digest.digest(passwordBytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return new SecretKeySpec(keyBytes, KEY_AES);
}
}
3.RSA
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Author:
* @CreateTime: 2023-09-13 16:50
* @Description: RSA加密解密工具类
*/
public class RSAUtils {
/**
* 非对称加密密钥算法
*/
public static final String KEY_ALGORITHM_RSA = "RSA";
/**
* 公钥
*/
private static final String RSA_PUBLIC_KEY = "RSAPublicKey";
/**
* 私钥
*/
private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";
/**
* RSA密钥长度
* 默认1024位,
* 密钥长度必须是64的倍数,
* 范围在512至65536位之间。
*/
private static final int KEY_SIZE = 1024;
/**
* 私钥解密
*
* @param data
* 待解密数据
* @param key
* 私钥
* @return byte[] 解密数据
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
throws Exception {
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
}
return cipher.doFinal(data);
}
/**
* 公钥解密
*
* @param data
* 待解密数据
* @param key
* 公钥
* @return byte[] 解密数据
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, byte[] key)
throws Exception {
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成公钥
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 公钥加密
*
* @param data
* 待加密数据
* @param key
* 公钥
* @return byte[] 加密数据
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] key)
throws Exception {
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0,remainSize=0;
while ((remainSize = data.length - i * blockSize) > 0) {
int inputLen = remainSize > blockSize?blockSize:remainSize;
cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
i++;
}
return raw;
}
return cipher.doFinal(data);
}
/**
* 私钥加密
*
* @param data
* 待加密数据
* @param key
* 私钥
* @return byte[] 加密数据
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
throws Exception {
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0,remainSize=0;
while ((remainSize = data.length - i * blockSize) > 0) {
int inputLen = remainSize > blockSize?blockSize:remainSize;
cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
i++;
}
return raw;
}
return cipher.doFinal(data);
}
/**
* 取得私钥
*
* @param keyMap
* 密钥Map
* @return key 私钥
* @throws Exception
*/
public static Key getPrivateKey(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PRIVATE_KEY);
}
/**
* 取得私钥
*
* @param keyMap
* 密钥Map
* @return byte[] 私钥
* @throws Exception
*/
public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PRIVATE_KEY).getEncoded();
}
/**
* 取得公钥
*
* @param keyMap
* 密钥Map
* @return key 公钥
* @throws Exception
*/
public static Key getPublicKey(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PUBLIC_KEY);
}
/**
* 取得公钥
*
* @param keyMap
* 密钥Map
* @return byte[] 公钥
* @throws Exception
*/
public static byte[] getPublicKeyByte(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PUBLIC_KEY).getEncoded();
}
/**
* 初始化密钥
* @param seed 种子
* @return Map 密钥Map
* @throws Exception
*/
public static Map<String,Key> initKey(byte[] seed)throws Exception{
// 实例化密钥对生成器
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM_RSA);
// 初始化密钥对生成器
keyPairGen.initialize(KEY_SIZE, new SecureRandom(seed) );
// 生成密钥对
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 封装密钥
Map<String, Key> keyMap = new HashMap<String, Key>(2);
keyMap.put(RSA_PUBLIC_KEY, publicKey);
keyMap.put(RSA_PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 初始化密钥
* @param seed 种子
* @return Map 密钥Map
* @throws Exception
*/
public static Map<String,Key> initKey(String seed)throws Exception{
return initKey(seed.getBytes());
}
/**
* 初始化密钥
*
* @return Map 密钥Map
* @throws Exception
*/
public static Map<String, Key> initKey() throws Exception {
return initKey(UUID.randomUUID().toString().getBytes());
}
public static PublicKey getPublicRSAKey(String key) throws Exception {
X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
return kf.generatePublic(x509);
}
public static PrivateKey getPrivateRSAKey(String key) throws Exception {
PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
return kf.generatePrivate(pkgs8);
}
}
4.MD5
package com.test.utils;
import org.springframework.util.DigestUtils;
/**
* @Author: zhangqingyun
* @CreateTime: 2023-09-13 16:24
* @Description: MD5加密解密工具类
*/
public class MD5Util {
/**
* MD5加密
*
* @param data 待加密数据
* @return byte[] 消息摘要
* @throws Exception
*/
public static byte[] encodeMD5(String data) throws Exception {
// 执行消息摘要
return DigestUtils.md5Digest(data.getBytes());
}
/**
* MD5加密
*
* @param data 待加密数据
* @return byte[] 消息摘要
* @throws Exception
*/
public static String encodeMD5Hex(String data) {
// 执行消息摘要
return DigestUtils.md5DigestAsHex(data.getBytes());
}
}