AES加密-解密

来源:互联网 发布:c4d软件介绍 编辑:程序博客网 时间:2024/06/05 09:50
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class AESUtil {

private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);




/**
* AES加密算法
*/
public AESUtil() {
}


/**
* 加密
*
* @param content
*            需要加密的内容
* @param keyWord
*            加密密钥
* @return byte[] 加密后的字节数组
* @throws Exception 
*/
public static byte[] encrypt(String content, String keyWord) throws Exception {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(keyWord.getBytes());
kgen.init(256,secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
logger.error("无此加密算法>>{}",e);
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
logger.error("AESUtil加密错误>>{}",e);
throw new Exception("AESUtil加密错误>>{}",e);
} catch (InvalidKeyException e) {
logger.error("加密公钥非法,请检查>>{}",e);
throw new Exception("加密密钥非法,请检查>>{}",e);
} catch (UnsupportedEncodingException e) {
logger.error("AESUtil加密错误>>{}",e);
throw new Exception("AESUtil加密错误>>{}",e);
} catch (IllegalBlockSizeException e) {
logger.error("明文长度非法>>{}",e);
throw new Exception("明文长度非法>>{}",e);
} catch (BadPaddingException e) {
logger.error("明文数据已损坏>>{}",e);
throw new Exception("明文数据已损坏>>{}",e);
}
}




/**
* 解密
*
* @param content
*            待解密内容
* @param keyWord
*            解密密钥
* @return byte[]
* @throws Exception 
*/
public static byte[] decrypt(byte[] content, String keyWord) throws Exception {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(keyWord.getBytes());
kgen.init(256, secureRandom);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
logger.error("无此加密算法>>{}",e);
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
logger.error("AESUtil加密错误>>{}",e);
throw new Exception("AESUtil加密错误>>{}",e);
} catch (InvalidKeyException e) {
logger.error("加密公钥非法,请检查>>{}",e);
throw new Exception("加密密钥非法,请检查>>{}",e);
} catch (IllegalBlockSizeException e) {
logger.error("明文长度非法>>{}",e);
throw new Exception("明文长度非法>>{}",e);
} catch (BadPaddingException e) {
logger.error("明文数据已损坏>>{}",e);
throw new Exception("明文数据已损坏>>{}",e);
}
}


public static void main(String[] args) throws Exception {
String content = "{\"scCode\":null,\"subScCode\":null,\"pcCode\":null,\"subPcCode\":null,\"bankCode\":null,\"scDate\":null,\"sysSeqId\":null," +
"\"sysDate\":null,\"pcDate\":null,\"pcSeqId\":null,\"merchantReferenceCode\":\"9999999999\",\"firstName\":\"你好\",\"lastName\":\"Doe\"," +
"\"country\":\"US\",\"state\":\"CA\",\"city\":\"Mountain View\",\"street1\":\"1295 Charleston Road\",\"postalCode\":\"94043\"," +
"\"email\":null,\"phoneNumber\":null,\"customerId\":null,\"ipAddress\":\"10.7.111.111\",\"cardAccountNumber\":\"4111111111111111\"," +
"\"cardType\":null,\"cardBin\":null,\"cardExpirationMonth\":\"12\",\"cardExpirationYear\":\"2020\",\"cvNumber\":null," +
"\"grandTotalAmount\":null,\"currency\":\"USD\",\"deviceFingerPrintId\":null,\"completeRoute\":null,\"departureDateTime\":null," +
"\"journeyType\":null,\"adultNum\":null,\"childNum\":null,\"selfFlag\":null,\"howLongDepart\":null,\"failureTimes\":null,\"ticketChnl\":null," +
"\"passengerInfoList\":null}";


String Key = "123456";


// 加密
System.out.println("加密前:" + content);
// String encryptResult = encrypttoStr(content, Key);
byte[] encryptByte=encrypt(content, Key);
String encryptResult=Base64Utils.encode(encryptByte);
System.out.println("加密后:" + encryptResult);
// 解密
byte[] decryptResult = decrypt(Base64Utils.decode(encryptResult), Key);
System.out.println("解密后:" + new String(decryptResult));

}
1 0