AES ECB实现加密案例

AES加解密,js前端和java后端实现

2019-06-13  本文已影响0人  坤kln

AES加解密,具体的介绍就不说了,觉得自己理解还不够,具体自己百科

直接上代码
Javascript前端使用CryptoJS库,这个库很多加密都有实现
下载地址:https://github.com/brix/crypto-js/releases
CDN可以看这个:https://www.bootcdn.cn/crypto-js/

// AES 加密,AES-128, AES-192, AES-256
// AES-128: key和iv都是16个字节,16*8=128bit
// AES-192: key和iv都是24个字节,24*8=128bit
// AES-256: key和iv都是32个字节,32*8=128bit
// iv 似乎一般都是纯数字
// 例如:AES_encrypt_CBC('需要加密的内容', '1234567890123456', '1234567890654321');
function AES_CBC_encrypt(message, key, iv) {
    // utf8字符串—>WordArray对象,WordArray是一个保存32位整数的数组,相当于转成了二进制
    let keyHex = CryptoJS.enc.Utf8.parse(key); //
    let ivHex = CryptoJS.enc.Utf8.parse(iv);
    let messageHex = CryptoJS.enc.Utf8.parse(message);
    let encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();// base64结果
    //return encrypted.ciphertext.toString();   // 二进制结果
}
// AES CBC模式解密
function AES_CBC_decrypt(messageBase64, key, iv) {
    // 如果加密后没有转成base64,那么先要转成base64再传入
    //let encryptedHexStr = CryptoJS.enc.Hex.parse(word);   // 从二进制文本转成二进制
    //messageBase64 = CryptoJS.enc.Base64.stringify(encryptedHexStr);    // 转成base64
    let keyHex = CryptoJS.enc.Utf8.parse(key);
    let ivHex = CryptoJS.enc.Utf8.parse(iv);
    let decrypt = CryptoJS.AES.decrypt(messageBase64, keyHex, {
        iv: ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}
// AES ECB模式加密,没有iv
function AES_ECB_encrypt(message, key) {
    // utf8字符串—>WordArray对象,WordArray是一个保存32位整数的数组,相当于转成了二进制
    let keyHex = CryptoJS.enc.Utf8.parse(key); //
    let messageHex = CryptoJS.enc.Utf8.parse(message);
    let encrypted = CryptoJS.AES.encrypt(messageHex, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();// base64结果
    //return encrypted.ciphertext.toString();   // 二进制结果
}
// AES ECB模式解密
function AES_ECB_decrypt(messageBase64, key) {
    // 如果加密后没有转成base64,那么先要转成base64再传入
    //let encryptedHexStr = CryptoJS.enc.Hex.parse(word);   // 从二进制文本转成二进制
    //messageBase64 = CryptoJS.enc.Base64.stringify(encryptedHexStr);    // 转成base64
    let keyHex = CryptoJS.enc.Utf8.parse(key);
    let decrypt = CryptoJS.AES.decrypt(messageBase64, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

java后端AES加解密

package com.CryptPacket;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;


/**
 * AES加解密工具
 * AES-128: key和iv都是16个字节,16*8=128bit,java似乎只支持AES-128
 */
public class AESCrypt {
    /**
     * AES CBC 加密
     * @param message 需要加密的字符串
     * @param key   密匙
     * @param iv    IV,需要和key长度相同
     * @return  返回加密后密文,编码为base64
     */
    public static String encryptCBC(String message, String key, String iv) {
        final String cipherMode = "AES/CBC/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            byte[] content = new byte[0];
            content = message.getBytes(charsetName);
            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
            //
            byte[] ivByte = iv.getBytes(charsetName);
            IvParameterSpec ivSpec = new IvParameterSpec(ivByte);

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] data = cipher.doFinal(content);
            final Base64.Encoder encoder = Base64.getEncoder();
            final String result = encoder.encodeToString(data);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * AES CBC 解密
     * @param messageBase64 密文,base64编码
     * @param key   密匙,和加密时相同
     * @param iv    IV,需要和key长度相同
     * @return  解密后数据
     */
    public static String decryptCBC(String messageBase64, String key, String iv) {
        final String cipherMode = "AES/CBC/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] messageByte = decoder.decode(messageBase64);

            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
            //
            byte[] ivByte = iv.getBytes(charsetName);
            IvParameterSpec ivSpec = new IvParameterSpec(ivByte);

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] content = cipher.doFinal(messageByte);
            String result = new String(content, charsetName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * AES ECB 加密
     * @param message 需要加密的字符串
     * @param key   密匙
     * @return  返回加密后密文,编码为base64
     */
    public static String encryptECB(String message, String key) {
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            byte[] content = new byte[0];
            content = message.getBytes(charsetName);
            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] data = cipher.doFinal(content);
            final Base64.Encoder encoder = Base64.getEncoder();
            final String result = encoder.encodeToString(data);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * AES ECB 解密
     * @param messageBase64 密文,base64编码
     * @param key   密匙,和加密时相同
     * @return  解密后数据
     */
    public static String decryptECB(String messageBase64, String key) {
        final String cipherMode = "AES/ECB/PKCS5Padding";
        final String charsetName = "UTF-8";
        try {
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] messageByte = decoder.decode(messageBase64);

            //
            byte[] keyByte = key.getBytes(charsetName);
            SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");

            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] content = cipher.doFinal(messageByte);
            String result = new String(content, charsetName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 测试
     */
    public static void Test()
    {
        String key = "1234567890123456";
        String iv = "1234567890000000";
        String msg = "这是一个测试这是一个测试这是一个测试";
        {
            String encrypt = AESCrypt.encryptCBC(msg, key, iv);
            System.out.println(encrypt);
            String decryptStr = AESCrypt.decryptCBC(encrypt, key, iv);
            System.out.println(decryptStr);
        }
        {
            String encrypt = AESCrypt.encryptECB(msg, key);
            System.out.println(encrypt);
            String decryptStr = AESCrypt.decryptECB(encrypt, key);
            System.out.println(decryptStr);
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读