import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* 对称加密
*
* @author mu.jie
* @date 2018/12/7 下午2:38
*/
public class SymmetricEncryptionUtil {
private static Logger logger = LoggerFactory.getLogger(SymmetricEncryptionUtil.class);
private static final String AES = "AES";
private static final String SHA1PRNG = "SHA1PRNG";
/**
* AES加密
* 1.构造密钥生成器
* 2.根据key初始化密钥生成器
* 3.产生密钥
* 4.创建和初始化密码器
* 5.内容加密
* 6.返回字符串
*/
public static String AESEncode(String key, String content) {
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
SecretKey secretKey = getSecretKey(key);
//6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(AES);
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
//9.根据密码器的初始化方式--加密:将数据加密
byte[] byteAES = cipher.doFinal(byteEncode);
//10.将加密后的数据转换为字符串
//11.将字符串返回
return new BASE64Encoder().encode(byteAES);
} catch (NoSuchAlgorithmException | IllegalBlockSizeException | NoSuchPaddingException | InvalidKeyException | BadPaddingException e) {
logger.error("AES Encode Error!", e);
}
//如果有错就返加nulll
return null;
}
/**
* AES解密
* 解密过程:
* 1.同加密1-5步
* 2.将加密后的字符串反纺成byte[]数组
* 3.将加密内容解密
*/
public static String AESDecode(String key, String content) {
try {
//1.构造密钥生成器,指定为AES算法,不区分大小写
SecretKey secretKey = getSecretKey(key);
//6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(AES);
//7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.DECRYPT_MODE, secretKey);
//8.将加密并编码后的内容解码成字节数组
byte[] byteContent = new BASE64Decoder().decodeBuffer(content);
/*
* 解密
*/
byte[] byteDecode = cipher.doFinal(byteContent);
return new String(byteDecode, StandardCharsets.UTF_8);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | IOException | BadPaddingException e) {
logger.error("AES Decode Error!", e);
}
//如果有错就返加nulll
return null;
}
/**
* 生成密钥
*
* @param key 私钥
* @return
* @throws NoSuchAlgorithmException
*/
private static SecretKey getSecretKey(String key) throws NoSuchAlgorithmException {
KeyGenerator keygen = KeyGenerator.getInstance(AES);
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
//SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;http://yangzb.iteye.com/blog/325264
// SecureRandom secureRandom = new SecureRandom(key.getBytes());
SecureRandom secureRandom = SecureRandom.getInstance(SHA1PRNG);
secureRandom.setSeed(key.getBytes());
keygen.init(128, secureRandom);
//3.产生原始对称密钥
SecretKey originalKey = keygen.generateKey();
//4.获得原始对称密钥的字节数组
byte[] raw = originalKey.getEncoded();
//5.根据字节数组生成AES密钥
return new SecretKeySpec(raw, AES);
}
public static void main(String[] args) {
String key = "123456";
JSONObject jsonObject = new JSONObject();
jsonObject.put("login", "admin");
jsonObject.put("pwd", "123456");
String content = jsonObject.toJSONString();
System.out.println("content:" + content);
String AESEncodeStr = AESEncode(key, content);
System.out.println("加密后:" + AESEncodeStr);
String decodeStr = AESDecode(key, AESEncodeStr);
System.out.println("解密后:" + decodeStr);
}
}