AES、RSA加解密工具类

一、AES加解密工具类

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;


/**
 * 

* AESUtils *

* Description: AES工具类 * * @date 2024/01/11 下午 05:01 */
public class AESUtils { public static void main(String[] args) throws Exception { String data = "{\n" + " \"code\": 10000,\n" + " \"result\": {\n" + " \"maxid\": 70714\n" + " }\n" + "}"; String seed = RandomStringUtils.randomAlphanumeric(30); System.out.println("==>seed:" + seed); System.out.println("-------------------"); String iv = RandomStringUtils.randomAlphanumeric(16); System.out.println("==>iv:" + iv); System.out.println("--------------------"); String encryptedData = AESUtils.encrypt(data, seed, iv); System.out.println("==>encryptedData:" + encryptedData); System.out.println("--------------------"); String decryptData = AESUtils.decrypt(encryptedData, seed, iv); System.out.println("==>decryptData:" + decryptData); System.out.println("-------------------"); } /** * 生成AES密钥 * * @param seed 种子 * @return 返回AES密钥 * @throws NoSuchAlgorithmException 异常信息 */ private static byte[] generateKey(String seed) throws Exception { SecureRandom secureRandom = new SecureRandom(); secureRandom.setSeed(seed.getBytes(StandardCharsets.UTF_8)); KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128, secureRandom); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } /** * AES加密 * * @param content 需要加密的内容 * @param seed 种子 * @param iv 偏移量,必须16位 * @return 返回加密后的内容 * @throws Exception 异常信息 */ public static String encrypt(String content, String seed, String iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] byteContent = content.getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKeySpec = new SecretKeySpec(generateKey(seed), "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); return Base64.encode(cipher.doFinal(byteContent)); } /** * AES解密 * * @param encryptedData 需要解密的内容 * @param seed 种子 * @param iv 偏移量,必须16位 * @return 返回解密后的内容 * @throws Exception 异常信息 */ public static String decrypt(String encryptedData, String seed, String iv) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] byteContent = Base64.decode(encryptedData); SecretKeySpec secretKeySpec = new SecretKeySpec(generateKey(seed), "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); return new String(cipher.doFinal(byteContent), StandardCharsets.UTF_8); } }

二、RSA加解密工具类

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
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.HashMap;
import java.util.Map;

/**
 * 

* RSAUtils *

* Description:RSA工具类 * * @date 2024/01/11 下午 02:59 */
public class RSAUtils { // 秘钥长度,应该为1024的整数倍,越大越慢,>=2048是安全的,<1024是不安全的 private static final int KEY_SIZE = 2048; // 加密算法RSA private static final String KEY_ALGORITHM = "RSA"; // 签名算法 private static final String SIGNATURE_ALGORITHM = "SHA256withRSA"; // 获取公钥的key private static final String PUBLIC_KEY = "RSAPublicKey"; // 获取私钥的key private static final String PRIVATE_KEY = "RSAPrivateKey"; // RSA最大加密明文大小 private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11; // RSA最大解密密文大小 private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8; public static void main(String[] args) throws Exception { // String seed = "$nN%^mT75*%jx^(Rbp)(Ydfp"; String seed = RandomStringUtils.randomAlphanumeric(30); System.out.println("seed:" + seed); System.out.println("----------------"); Map<String, String> keyPair = RSAUtils.genKeyPair(seed); String publicKey = keyPair.get(PUBLIC_KEY); String privateKey = keyPair.get(PRIVATE_KEY); System.out.println("publicKey:" + publicKey); System.out.println("privateKey:" + privateKey); System.out.println("-----------------"); String data = "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。\r\n" + "部署 (Deployment) 用来描述期望应用达到的目标状态,主要用来描述无状态应用,副本的数量和状态由其背后的控制器来维护,确保状态与定义的期望状态一致。您可以增加副本数量来满足更高负载;回滚部署的版本来消除程序的错误修改;创建自动伸缩器来弹性应对不同场景下的负载。"; String publicEncrypt = RSAUtils.encryptByPublicKey(data, publicKey); System.out.println("公钥加密后的数据:" + publicEncrypt); String privateDecrypt = RSAUtils.decryptByPrivateKey(publicEncrypt, privateKey); System.out.println("私钥解密后的数据:" + privateDecrypt); System.out.println("--------------------"); String privateKeyEncrypt = RSAUtils.encryptByPrivateKey(data, privateKey); System.out.println("私钥加密后的数据:" + privateKeyEncrypt); String publicDecrypt = RSAUtils.decryptByPublicKey(privateKeyEncrypt, publicKey); System.out.println("公钥解密后的数据:" + publicDecrypt); System.out.println("-------------------"); String singData = RSAUtils.sign("111", privateKey); System.out.println("私钥签名后的数据:" + singData); boolean isSign = RSAUtils.verify("111", publicKey, singData); System.out.println("签名是否正确:" + isSign); System.out.println("------------------"); } /** * 生成公钥和私钥 * * @param seed 种子 * @return * @throws Exception */ public static Map<String, String> genKeyPair(String seed) throws Exception { // 如果指定seed,那么secureRandom结果是一样的,所以生成的公私钥也永远不会变 SecureRandom secureRandom = new SecureRandom(); secureRandom.setSeed(seed.getBytes()); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(KEY_SIZE, secureRandom); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, String> keyMap = new HashMap<>(2); keyMap.put(PUBLIC_KEY, Base64.encode(publicKey.getEncoded())); keyMap.put(PRIVATE_KEY, Base64.encode(privateKey.getEncoded())); return keyMap; } /** * 对数据进行签名 * * @param data 待签名的数据 * @param privateKey 私钥 * @return 对数据生成签名 * @throws Exception */ public static String sign(String data, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data.getBytes(StandardCharsets.UTF_8)); return Base64.encode(signature.sign()); } /** * 验签 * * @param data 签名之前的数据 * @param publicKey 公钥 * @param sign 签名之后的数据 * @return 验签是否成功 * @throws Exception */ public static boolean verify(String data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicK); signature.update(data.getBytes(StandardCharsets.UTF_8)); return signature.verify(Base64.decode(sign)); } /** * 用私钥对数据进行解密 * * @param encryptedData 使用公钥加密过的数据 * @param privateKey 私钥 * @return 解密后的数据 * @throws Exception */ public static String decryptByPrivateKey(String encryptedData, String privateKey) throws Exception { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateK); byte[] dataBytes = Base64.decode(encryptedData); int inputLen = dataBytes.length; int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(dataBytes, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(dataBytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } return new String(out.toByteArray(), StandardCharsets.UTF_8); } } /** * 公钥解密 * * @param encryptedData 使用私钥加密过的数据 * @param publicKey 公钥 * @return 解密后的数据 * @throws Exception */ public static String decryptByPublicKey(String encryptedData, String publicKey) throws Exception { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); byte[] dataBytes = Base64.decode(encryptedData); int inputLen = dataBytes.length; int offSet = 0; byte[] cache; int i = 0; // 对数据分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(dataBytes, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(dataBytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } return new String(out.toByteArray(), StandardCharsets.UTF_8); } } /** * 公钥加密 * * @param data 需要加密的数据 * @param publicKey 公钥 * @return 使用公钥加密后的数据 * @throws Exception */ public static String encryptByPublicKey(String data, String publicKey) throws Exception { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] keyBytes = Base64.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); byte[] dataBytes = data.getBytes(); int inputLen = dataBytes.length; int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(dataBytes, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(dataBytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } return Base64.encode(out.toByteArray()); } } /** * 私钥加密 * * @param data 待加密的数据 * @param privateKey 私钥 * @return 使用私钥加密后的数据 * @throws Exception */ public static String encryptByPrivateKey(String data, String privateKey) throws Exception { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { byte[] keyBytes = Base64.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateK); byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); int inputLen = dataBytes.length; int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(dataBytes, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(dataBytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } return Base64.encode(out.toByteArray()); } } }

你可能感兴趣的:(工具类,java)