package com.thinkgem.jeesite.modules.emindsoft.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AesEncodeUtil {
//初始向量
public static final String VIPARA = "aabbccddeeffgghh"; //AES 為16bytes. DES 為8bytes
//編碼方式
public static final String bm = "UTF-8";
//私鑰
private static final String ASE_KEY="aabbccddeeffgghh"; //AES固定格式為128/192/256 bits.即:16/24/32bytes卤唉。DES固定格式為128bits,即8bytes仁期。
/**
* 加密
*
* @param cleartext
* @return
*/
public static String encrypt(String cleartext) {
//加密方式: AES128(CBC/PKCS5Padding) + Base64, 私鑰:aabbccddeeffgghh
try {
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
//兩個(gè)參數(shù)桑驱,第一個(gè)為私鑰字節(jié)數(shù)組, 第二個(gè)為加密方式 AES或者DES
SecretKeySpec key = new SecretKeySpec(ASE_KEY.getBytes(), "AES");
//實(shí)例化加密類(lèi)跛蛋,參數(shù)為加密方式熬的,要寫(xiě)全
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //PKCS5Padding比PKCS7Padding效率高,PKCS7Padding可支持IOS加解密
//初始化赊级,此方法可以采用三種方式押框,按加密算法要求來(lái)添加。(1)無(wú)第三個(gè)參數(shù)(2)第三個(gè)參數(shù)為SecureRandom random = new SecureRandom();中random對(duì)象理逊,隨機(jī)數(shù)橡伞。(AES不可采用這種方法)(3)采用此代碼中的IVParameterSpec
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
//加密操作,返回加密后的字節(jié)數(shù)組,然后需要編碼晋被。主要編解碼方式有Base64, HEX, UUE,7bit等等兑徘。此處看服務(wù)器需要什么編碼方式
byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));
return new BASE64Encoder().encode(encryptedData);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 解密
*
* @param encrypted
* @return
*/
public static String decrypt(String encrypted) {
try {
byte[] byteMi = new BASE64Decoder().decodeBuffer(encrypted);
IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
SecretKeySpec key = new SecretKeySpec(
ASE_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//與加密時(shí)不同MODE:Cipher.DECRYPT_MODE
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte[] decryptedData = cipher.doFinal(byteMi);
return new String(decryptedData, bm);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 測(cè)試
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String content = "98.5674{“”:\"nishi\",\"我——-!@#¥%……&*$\":\"\"}";
// 加密
System.out.println("加密前:" + content);
String encryptResult = encrypt(content);
System.out.println("加密后:" + new String(encryptResult));
// 解密
String decryptResult = decrypt(encryptResult);
System.out.println("解密后:" + new String(decryptResult));
}
}
網(wǎng)盤(pán)/工作/總結(jié)////