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;
        }
    }
}

你可能感兴趣的:(加密解密)