欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

AES-128-CBC 加密

程序员文章站 2024-03-14 14:12:58
...
package com.ikang.util;

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

import org.apache.commons.codec.binary.Base64;

/**
 * AES/CBC/PKCS5Padding 对称加密
 *
 * @author jia
 */
public class AES_CBC {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 数据加密
     *
     * @param srcData
     * @param key
     * @param iv
     * @return
     */
    public static String encrypt(String srcData, byte[] key, byte[] iv) {
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher;
        String encodeBase64String = null;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
            byte[] encData = cipher.doFinal(srcData.getBytes());
            encodeBase64String = Base64.encodeBase64String(encData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodeBase64String;
    }

    /**
     * 数据解密
     *
     * @param encDataStr
     * @param key
     * @param iv
     * @return
     */
    public static String decrypt(String encDataStr, byte[] key, byte[] iv) {
        byte[] encData = Base64.decodeBase64(encDataStr);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        Cipher cipher;
        byte[] decbbdt = null;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv));
            decbbdt = cipher.doFinal(encData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(decbbdt);
    }

    public static void main(String[] args) throws Exception {
        String key = "0e404157ade3445b219fab915e584619".substring(0, 16);
        String iv = "0e404157ade3445b219fab915e584619".substring(16, 32);
        String s2 = "12345678ilkljklkjv";
        System.out.println("加密前: " + s2);
        String encrypt = AES_CBC.encrypt(s2, key.getBytes(), iv.getBytes());
        System.out.println("加密后: " + new String(encrypt));
        String decrypt = AES_CBC.decrypt(encrypt, key.getBytes(), iv.getBytes());
        System.out.println("解密后: " + decrypt);
    }
}