java的AES對稱加密和解密,有偏移量


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做轉碼。
 } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM