1. 程式人生 > >java Aes加解密

java Aes加解密

java中加AES解密的方式比較簡單,本示例展示CBC模式AES在java中的加解密

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;

public class AesTest {
    public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    public static final String KEY_ALGORITHM = "AES";

    public static void main(String[] args) throws IOException {
        //key必須是16的倍數,過長會報錯,與jre環境local_policy.jar, US_export_policy.jar有關
        SecretKey key = restoreSecretKey("14785236963698521478523696369852");
        byte[] iv = "1236547896325474".getBytes();
        System.out.println(iv.length);
        byte[] encodeBytes = AesCbcEncode("Hello World!".getBytes(), key, iv);
        byte[] decodeBytes = AesCbcDecode(encodeBytes, key, iv);
        System.out.println(new String(decodeBytes));
    }

    /**
     * 還原金鑰
     * @param keyWord
     * @return
     */
    public static SecretKey restoreSecretKey(String keyWord) {
        SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), KEY_ALGORITHM);
        return key;
    }

    public static byte[] AesCbcEncode(byte[] plainText, SecretKey key, byte[] IVParameter) {
        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);

            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
            return cipher.doFinal(plainText);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * CBC 解密
     * @param decodedText
     * @param key
     * @param IVParameter
     * @return
     */
    public static byte[] AesCbcDecode(byte[] decodedText, SecretKey key, byte[] IVParameter) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);
        try {
            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
            return cipher.doFinal(decodedText);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}