java实现多种加密模式的AES算法-总有一种你用的着

https://blog.csdn.net/u013871100/article/details/80100992

AES-128位-无向量-ECB/PKCS7Padding


package com.debug.steadyjack.springbootMQ.server.util;
 
import org.apache.commons.codec.binary.Base64;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
 
/**
 * AES加密算法util
 * Created by steadyjack on 2018/4/21.
 */
public class AESUtil {
 
    private static final String EncryptAlg ="AES";
 
    private static final String Cipher_Mode="AES/ECB/PKCS7Padding";
 
    private static final String Encode="UTF-8";
 
    private static final int Secret_Key_Size=32;
 
    private static final String Key_Encode="UTF-8";
 
    /**
     * AES/ECB/PKCS7Padding 加密
     * @param content
     * @param key 密钥
     * @return aes加密后 转base64
     * @throws Exception
     */
    public static String aesPKCS7PaddingEncrypt(String content, String key) throws Exception {
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 
            Cipher cipher = Cipher.getInstance(Cipher_Mode);
            byte[] realKey=getSecretKey(key);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(realKey,EncryptAlg));
            byte[] data=cipher.doFinal(content.getBytes(Encode));
            String result=new Base64().encodeToString(data);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("AES加密失败:content=" +content +" key="+key);
        }
    }
 
    /**
     * AES/ECB/PKCS7Padding 解密
     * @param content
     * @param key 密钥
     * @return 先转base64 再解密
     * @throws Exception
     */
    public static String aesPKCS7PaddingDecrypt(String content, String key) throws Exception {
        try {
            //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
 
            byte[] decodeBytes=Base64.decodeBase64(content);
 
            Cipher cipher = Cipher.getInstance(Cipher_Mode);
            byte[] realKey=getSecretKey(key);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(realKey,EncryptAlg));
            byte[] realBytes=cipher.doFinal(decodeBytes);
 
            return new String(realBytes, Encode);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("AES解密失败:Aescontent = " +e.fillInStackTrace(),e);
        }
    }
 
    /**
     * 对密钥key进行处理:如密钥长度不够位数的则 以指定paddingChar 进行填充;
     * 此处用空格字符填充,也可以 0 填充,具体可根据实际项目需求做变更
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] getSecretKey(String key) throws Exception{
        final byte paddingChar=' ';
 
        byte[] realKey = new byte[Secret_Key_Size];
        byte[] byteKey = key.getBytes(Key_Encode);
        for (int i =0;i<realKey.length;i++){
            if (i<byteKey.length){
                realKey[i] = byteKey[i];
            }else {
                realKey[i] = paddingChar;
            }
        }
 
        return realKey;
    }
}
————————————————

public static void main(String[] args) throws Exception{
        //密钥 加密内容(对象序列化后的内容-json格式字符串)
        String key="debug";
        String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";
 
        String encryptRes=aesPKCS7PaddingEncrypt(content,key);
        System.out.println(String.format("加密结果:%s ",encryptRes));
 
        String decryptRes=aesPKCS7PaddingDecrypt(encryptRes,key);
        System.out.println(String.format("解密结果:%s ",decryptRes));
    }


AES-128位-有向量-CBC/PKCS5Padding

package com.debug.steadyjack.springbootMQ.server.util;
 
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;
 
/**
 * AES加解密工具
 * Created by steadyjack on 2018/2/9.
 */
public class EncryptUtil {
 
    private static final String CipherMode="AES/CBC/PKCS5Padding";
 
    private static final String SecretKey="debug";
 
    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 {
            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;
    }
 
    public static void main(String[] args) throws Exception{
        //密钥 加密内容(对象序列化后的内容-json格式字符串)
        String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";
 
        String encryptText=encrypt(content);
        String decryptText=decrypt(encryptText);
        System.out.println(String.format("明文:%s \n加密结果:%s \n解密结果:%s ",content,encryptText,decryptText));
    }
}
posted @ 2019-12-23 15:44  antball  阅读(1085)  评论(0编辑  收藏  举报