JAVA AES128

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author cold
 */
public class AES128 {

    // 加密算法
    private static String ALGO = "AES";
    private static String ALGO_MODE = "AES/CBC/NoPadding";

    /**
     * 加密
     * @param Data 待加密字符串
     * @param akey 16位隨機字符串
     * @param aiv  16位隨機字符串
     * @return 
     * @throws Exception
     */
    public static String encrypt(String Data,String akey,String aiv) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance(ALGO_MODE);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = Data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(akey.getBytes("utf-8"), ALGO);
            IvParameterSpec ivspec = new IvParameterSpec(aiv.getBytes("utf-8"));
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            String EncStr = new sun.misc.BASE64Encoder().encode(encrypted);
            return EncStr;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密
     * @param encryptedData 待加密字符串
     * @param akey 和加密使用同一個key
     * @param aiv  和加密使用同一個iv
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedData,String akey,String aiv) throws Exception {
        try {
            byte[] encrypted1 = new sun.misc.BASE64Decoder().decodeBuffer(encryptedData);

            Cipher cipher = Cipher.getInstance(ALGO_MODE);
            SecretKeySpec keyspec = new SecretKeySpec(akey.getBytes("utf-8"), ALGO);
            IvParameterSpec ivspec = new IvParameterSpec(aiv.getBytes("utf-8"));

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
發佈了44 篇原創文章 · 獲贊 66 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章