Java之AES加解密示例

来源:互联网 发布:便宜的瑜伽垫 知乎 编辑:程序博客网 时间:2024/06/07 01:36

Java之AES加解密

//package jdbc.pro.lin;import java.security.NoSuchAlgorithmException;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;// import org.apache.commons.codec.binary.Base64;public class MyAES {    /**     * 注意key和加密用到的字符串是不一样的 加密还要指定填充的加密模式和填充模式 AES密钥可以是128或者256,加密模式包括ECB, CBC等     * ECB模式是分组的模式,CBC是分块加密后,每块与前一块的加密结果异或后再加密 第一块加密的明文是与IV变量进行异或     */    public static final String KEY_ALGORITHM = "AES";    public static final String ECB_CIPHER_ALGORITHM = "AES/ECB/NoPadding";    public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/NoPadding";    // 如果是ECB模式的话就不需要IvParameterSpec    static byte[] iv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };    private static IvParameterSpec ivspec = new IvParameterSpec(iv);    /**     * IV(Initialization Value)是一个初始值,对于CBC模式来说,它必须是随机选取并且需要保密的     * 而且它的长度和密码分组相同(比如:对于AES 128为128位,即长度为16的byte类型数组)     *      */    public static void main(String[] args) {        // generateAESSecretKey();        byte[] secretBytes = {54, 26, -75, -114, -54, -33, 97, -84, -68, 63, 14, -12, 96, 40, -54, 87};        SecretKey key = restoreSecretKey(secretBytes);        byte[] decodeText = { (byte) 0xA6,(byte) 0xA7,(byte) 0xA0,(byte) 0xB4,                0x02,0x31,0x15,(byte) 0x9F,(byte) 0xD7,(byte) 0x83,0x38,0x14,(byte) 0xFC,0x4B,(byte) 0xE9,(byte) 0xCD};        byte[] encodedText = AesEcbEncode(decodeText, key);        System.out.println("\n加密:");        // Print the cypherText        for (int i = 0; i < 16; i++) {            System.out.printf("%02X ", encodedText[i]);        }        byte[] bb = {91, -33, 25, -23, -59, 11, 97, 40, -116, 22, -119, -95, 96, 105, -46, -6 };        decodeText = AesEcbDecode(bb, key);        System.out.print("\n解密:\n");        // Print the plainText        for (int i = 0; i < 16; i++) {            System.out.printf("%02X ", decodeText[i]);        }    }    /**     * 使用ECB模式进行加密。 加密过程三步走: 1. 传入算法,实例化一个加解密器 2. 传入加密模式和密钥,初始化一个加密器 3.     * 调用doFinal方法加密     *      * @param plainText     * @return     */    public static byte[] AesEcbEncode(byte[] plainText, SecretKey key) {        try {            Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM);            cipher.init(Cipher.ENCRYPT_MODE, key/* , ivspec */);            return cipher.doFinal(plainText);        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    /**     * 1.创建一个KeyGenerator 2.调用KeyGenerator.generateKey方法     * 由于某些原因,这里只能是128,如果设置为256会报异常,原因在下面文字说明     *      * @return     */    public static byte[] generateAESSecretKey() {        KeyGenerator keyGenerator;        try {            keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);            // keyGenerator.init(256);            return keyGenerator.generateKey().getEncoded();        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }        return null;    }    /**     * 还原密钥     *      * @param secretBytes     * @return     */    public static SecretKey restoreSecretKey(byte[] secretBytes) {        SecretKey secretKey = new SecretKeySpec(secretBytes, KEY_ALGORITHM);        return secretKey;    }    public static byte[] AesEcbDecode(byte[] decodedText, SecretKey key) {        try {            Cipher cipher = Cipher.getInstance(ECB_CIPHER_ALGORITHM);            cipher.init(Cipher.DECRYPT_MODE, key/* , ivspec */);            return (cipher.doFinal(decodedText));        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}
原创粉丝点击