接上一篇企业级AES加解密
废话不多说,直接上代码,复制粘贴即可用
package com.xx.xx.utils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* 加密工具类
*
* @author yuan
*/
public class CipherUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(CipherUtil.class);
protected static final String SECRET_KEY = "sdlfjo234L32fv0o9iNG0LL!!*&1%$#@";
/**
* 非对称加密
*/
private static Rsa rsa;
/**
* 获取非对称加密算法
*
* @return 加密算法
*/
public static Rsa rsa() {
if (null == rsa) {
rsa = new Rsa();
}
return rsa;
}
/**
* 非对称加密工具类
*/
public static class Rsa {
private static final String DEFAULT_CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
private static Cipher cipher;
private static KeyPair keyPair;
private static PublicKey publicKey;
private static PrivateKey privateKey;
private synchronized Cipher cipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
if (null == cipher) {
cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
}
return cipher;
}
private synchronized KeyPair keyPair(String key) throws NoSuchAlgorithmException {
if (null == keyPair) {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
// 指定算法名称,不同的系统上生成的key是相同的。
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(key.getBytes(StandardCharsets.UTF_8));
generator.initialize(1024, random);
keyPair = generator.generateKeyPair();
}
return keyPair;
}
private synchronized PublicKey publicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
if (null == publicKey) {
publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyPair(SECRET_KEY).getPublic().getEncoded()));
}
return publicKey;
}
private PrivateKey privateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
if (null == privateKey) {
privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(keyPair(SECRET_KEY).getPrivate().getEncoded()));
}
return privateKey;
}
public synchronized String encrypt(String content) {
try {
cipher().init(Cipher.ENCRYPT_MODE, publicKey());
return byte2Base64(cipher.doFinal(content.getBytes()));
} catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException e) {
LOGGER.error("数据加密失败,stack info=" + ExceptionUtils.getFullStackTrace(e));
throw new ArithmeticException("数据加密失败");
}
}
public synchronized String decrypt(String content) {
try {
cipher().init(Cipher.DECRYPT_MODE, privateKey());
return new String(cipher.doFinal(base642Byte(content)));
} catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException e) {
LOGGER.error("数据解密失败,stack info=" + ExceptionUtils.getFullStackTrace(e));
throw new ArithmeticException("数据解密失败");
}
}
}
/**
* 字节数组转Base64编码
*
* @param bytes 内容字节码
* @return base64编码
*/
public static String byte2Base64(byte[] bytes) {
return Base64Utils.encodeToUrlSafeString(bytes);
}
/**
* Base64编码转字节数组
*
* @param base64Key base64编码
* @return 字节数组
*/
public static byte[] base642Byte(String base64Key) {
return Base64Utils.decodeFromUrlSafeString(base64Key);
}
public static void main(String[] args) {
String content = "D:\\attachment\\file.docx";
System.out.println("原文=" + content);
String s1 = CipherUtil.rsa().encrypt(content);
System.out.println("加密结果=" + s1);
System.out.println("解密结果=" + CipherUtil.rsa().decrypt(s1));
}
}