import java.math.BigDecimal; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.codehaus.jettison.json.JSONObject; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * AES对称加密和解密,有偏移量 * @author tyg * @date 2018年6月28日下午12:48:01 */ @SuppressWarnings("restriction") public class AESUtils { // 密匙
private static final String KEY = "f4k9f5w7f8g4er26"; // 偏移量
private static final String OFFSET = "5e8y6w45ju8w9jq8"; // 编码
private static final String ENCODING = "UTF-8"; //算法
private static final String ALGORITHM = "AES"; // 默认的加密算法
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * 加密 * @param data * @return * @throws Exception * @return String * @author tyg * @date 2018年6月28日下午2:50:35 */
public static String encrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM); IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING)); return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
} /** * 解密 * @param data * @return * @throws Exception * @return String * @author tyg * @date 2018年6月28日下午2:50:43 */
public static String decrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("ASCII"), ALGORITHM); IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] buffer = new BASE64Decoder().decodeBuffer(data); byte[] encrypted = cipher.doFinal(buffer); return new String(encrypted, ENCODING);//此处使用BASE64做转码。
}