基于Java的AES加解密demo

package cn.com.pubinfo.sifa.mediate.util;

import org.apache.shiro.codec.Base64;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class AESUtils {

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    /**
     * SecretKeySpec类是KeySpec接口的实现类,用于构建秘密密钥规范
     */
    private SecretKeySpec key;
    
    private SecretKey key2;

    public AESUtils(String hexKey) {
    	try {
    		//创建密钥生成器  
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);  
            //初始化密钥  
            keyGenerator.init(128,new SecureRandom(hexKey.getBytes()));  
            //生成密钥  
            key2 = keyGenerator.generateKey();  
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
        key = new SecretKeySpec(hexKey.getBytes(), ALGORITHM);
    }

    /**
     * AES加密
     * @param data
     * @return
     * @throws Exception
     */
    public String encryptData(String data) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // 创建密码器
        cipher.init(Cipher.ENCRYPT_MODE, key2);// 初始化
        return new Base64().encodeToString(cipher.doFinal(data.getBytes()));
    }

    /**
     * AES解密
     * @param base64Data
     * @return
     * @throws Exception
     */
    public String decryptData(String base64Data) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.DECRYPT_MODE, key2);
        return new String(cipher.doFinal(new Base64().decode(base64Data)));
    }

    public static String decrypt(String base64Data,String key) {
        AESUtils aesUtil = new AESUtils(key);
        String result = null;
        try {
            result =  aesUtil.decryptData(base64Data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String encrypt(String data,String key) {
        AESUtils aesUtil = new AESUtils(key);
        String result = null;
        try {
            result =  aesUtil.encryptData(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * hex字符串 转 byte数组
     * @param s
     * @return
     */
    private static byte[] hex2byte(String s) {
        if (s.length() % 2 == 0) {
            return hex2byte (s.getBytes(), 0, s.length() >> 1);
        } else {
            return hex2byte("0"+s);
        }
    }

    private static byte[] hex2byte (byte[] b, int offset, int len) {
        byte[] d = new byte[len];
        for (int i=0; i<len*2; i++) {
            int shift = i%2 == 1 ? 0 : 4;
            d[i>>1] |= Character.digit((char) b[offset+i], 16) << shift;
        }
        return d;
    }

    public static void main(String[] args) throws Exception {
        AESUtils util = new AESUtils("ZMIQHUNJIZIHQIHEXFBO"); // 密钥
        System.out.println("cardNo:"+util.encryptData("{\"serialNumber\":\"330211JD04000017092001003JKLBNTH\",\"status\":36}")); // 加密
        System.out.println("exp:"+util.decryptData("psVhPX1LJxW90Ol7LsCLTSAWNHwbsW90fWdrJylc+y+L5TTkMPj1N7gCb4BGC73RDPpaX1pS4XVMlP67CQTzow==")); // 解密
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值