java中使用AES加密(加密模式為CBC,填充方式:AES/CBC/PKCS7Padding,密鑰長度32位)


首先導入依賴

<dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
 </dependency>

  工具類

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

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Security;

/**
 * AES加解密工具
 */
public class EncryptUtil {
    private static final String CipherMode="AES/CBC/PKCS7Padding";
 
    private static final String SecretKey="key";
 
    private static final Integer IVSize=16;
 
    private static final String EncryptAlg ="AES";
 
    private static final String Encode="UTF-8";
 
    private static final int SecretKeySize=32;
 
    private static final String Key_Encode="UTF-8";
 
    /**
     * 創建密鑰
     * @return
     */
    private static SecretKeySpec createKey(){
        StringBuilder sb=new StringBuilder(SecretKeySize);
        sb.append(SecretKey);
        if (sb.length()>SecretKeySize){
            sb.setLength(SecretKeySize);
        }
        if (sb.length()<SecretKeySize){
            while (sb.length()<SecretKeySize){
                sb.append(" ");
            }
        }
        try {
            byte[] data=sb.toString().getBytes(Encode);
            return new SecretKeySpec(data, EncryptAlg);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 創建16位向量: 不夠則用0填充
     * @return
     */
    private static IvParameterSpec createIV() {
        StringBuffer sb = new StringBuffer(IVSize);
        sb.append(SecretKey);
        if (sb.length()>IVSize){
            sb.setLength(IVSize);
        }
        if (sb.length()<IVSize){
            while (sb.length()<IVSize){
                sb.append("0");
            }
        }
        byte[] data=null;
        try {
             data=sb.toString().getBytes(Encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new IvParameterSpec(data);
    }
 
    /**
     * 加密:有向量16位,結果轉base64
     * @param context
     * @return
     */
    public static String encrypt(String context) {
        try {
        //下面這行在進行PKCS7Padding加密時必須加上,否則報錯 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); byte[] content=context.getBytes(Encode); SecretKeySpec key = createKey(); Cipher cipher = Cipher.getInstance(CipherMode); cipher.init(Cipher.ENCRYPT_MODE, key, createIV()); byte[] data = cipher.doFinal(content); String result= Base64.encodeBase64String(data); return result; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 解密 * @param context * @return */ public static String decrypt(String context) { try { byte[] data=Base64.decodeBase64(context); SecretKeySpec key = createKey(); Cipher cipher = Cipher.getInstance(CipherMode); cipher.init(Cipher.DECRYPT_MODE, key, createIV()); byte[] content = cipher.doFinal(data); String result=new String(content,Encode); return result; } catch (Exception e) { e.printStackTrace(); } return null; } } 
注意:PKCS7Padding加密時需要調用BouncyCastleProvider讓java支持PKCS7Padding
相應的依賴
  <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk16</artifactId>
            <version>1.46</version>
        </dependency>

  參考文章來源於:https://blog.csdn.net/u013871100/article/details/80100992

  還可參考:https://www.cnblogs.com/wrcold520/p/8931034.html






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM