该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
package com.chestnut.funshop.util;
import github.cweijan.ultimate.util.Log;
import org.apache.commons.codec.binary.Base64;
import sun.security.krb5.internal.crypto.Aes128;
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;
public class AES {
private static final String KEY_ALGORITHM = "AES";
private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String IV = "qeO9xrUlSC7bK2s3";
private static KeyGenerator kg = null;
static {
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
/**
* 进行AES加密
*
* @param content 待加密内容
* @param key AES密钥
* @return 已加密字符串
*/
public static String entrypt(String content, String key) {
try {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key), new IvParameterSpec(IV.getBytes()));
byte[] result = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));// 加密
return Base64.encodeBase64String(result);
} catch (Exception ex) {
Log.getLogger().error(ex.getMessage());
}
return null;
}
/**
* 进行AES解密
*
* @param entryptContent 待加密内容
* @param key AES密钥
* @return 已解密字符串
*/
public static String detrypt(String entryptContent, String key) {
try {
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key), new IvParameterSpec(IV.getBytes()));
byte[] result = cipher.doFinal(Base64.decodeBase64(entryptContent));
return new String(result, StandardCharsets.UTF_8);
} catch (Exception ex) {
Log.getLogger().error(ex.getMessage());
}
return null;
}
public static void main(String[] args) {
String helo = AES.entrypt("helo", "1");
System.out.println(AES.detrypt(helo, "1"));
helo = AES.entrypt("helo", "1");
System.out.println(AES.detrypt(helo, "1"));
}
/**
*
*/
private static SecretKeySpec getSecretKey(final String password) {
if (password.length() % 16 == 0) {
return new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);
}
try {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password.getBytes());
kg.init(128, secureRandom);
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
Log.getLogger().error(ex.getMessage(), ex);
}
return null;
}
private AES() {
}
}