AES加密解密

AES.java类代码

package com.apex.esb.client.http.util; /**
 * Created by Administrator on 2018/3/8.
 */

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import common.Logger;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;

/**
 * @version V1.0
 * @desc AES 加密工具类
 */
public class AES {
    private static final Logger LOG = Logger.getLogger(AES.class);
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";//默认的加密算法


    private static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @param password 加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password) {
        try {
            String randomKey = getRandomString(16);

            //动态秘钥密文
            byte[] signaturePart1 = encryptInner(randomKey.getBytes("utf-8"), password);

            //文本秘钥密文
            byte[] signaturePart2 = encryptInner(content.getBytes("utf-8"), randomKey);

            byte[] data = new byte[signaturePart1.length + signaturePart2.length];
            System.arraycopy(signaturePart1, 0, data, 0, signaturePart1.length);
            System.arraycopy(signaturePart2, 0, data, signaturePart1.length, signaturePart2.length);
            return Base64.encode(data);//通过Base64转码返回
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
        return null;
    }

    private static byte[] encryptInner(byte[] content, String password) {
        try {

            //计算秘钥字节
            byte[] key = fromHexString(MD5.MD5(password));

            //创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM), new IvParameterSpec(key));// 初始化为加密模式的密码器

            //计算密文字节
            byte[] result = cipher.doFinal(content);

            return result;
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
        return null;
    }

    private static byte[] decryptInner(byte[] content, String password) {
        try {

            //计算秘钥字节
            byte[] key = fromHexString(MD5.MD5(password));

            //创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM), new IvParameterSpec(key));// 初始化为加密模式的密码器

            //计算密文字节
            byte[] result = cipher.doFinal(content);

            return result;
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param password
     * @return
     */
    public static String decrypt(String content, String password) {
        try {
            //动态秘钥+密文
            byte[] bytes = Base64.decode(content);

            //拆解动态秘钥+密文
            byte[] randomKeyByte = new byte[32];
            byte[] contentByte = new byte[bytes.length - 32];
            System.arraycopy(bytes, 0, randomKeyByte, 0, 32);
            System.arraycopy(bytes, 32, contentByte, 0, bytes.length - 32);


            String randomKey = new String(decryptInner(randomKeyByte, password), "utf-8");

            return new String(decryptInner(contentByte, randomKey), "utf-8");
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }

        return null;
    }


    public static byte[] fromHexString(String input) {
        if(input == null) {
            return null;
        } else if((input.length() & 1) == 1) {
            throw new IllegalArgumentException("hexUtils.fromHex.oddDigits");
        } else {
            char[] inputChars = input.toCharArray();
            byte[] result = new byte[input.length() >> 1];

            for(int i = 0; i < result.length; ++i) {
                int upperNibble = getDec(inputChars[2 * i]);
                int lowerNibble = getDec(inputChars[2 * i + 1]);
                if(upperNibble < 0 || lowerNibble < 0) {
                    throw new IllegalArgumentException("hexUtils.fromHex.nonHex");
                }

                result[i] = (byte)((upperNibble << 4) + lowerNibble);
            }

            return result;
        }
    }
    private static final int[] DEC = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15};

    public static int getDec(int index) {
        try {
            return DEC[index - 48];
        } catch (ArrayIndexOutOfBoundsException var2) {
            return -1;
        }
    }
}

 

Test.java测试类代码

package com.apex.esb.client;

import com.apex.esb.client.http.util.AES;
/**
 * Created by Administrator on 2018/8/3.
 */
public class Test {

    public static void main(String[] args)  {

        //加密
        String password = "12ergergfdgfdg";        //用户名密码加密
        String signature =  "password=" + password + "&timestamp=" + System.currentTimeMillis();//增加时间搓
        String secret = "100000000000054";//用户的BID (加密和解密的公共秘钥)
        signature = AES.encrypt(signature, secret);//加密的密码

        System.out.println("加密后的密码:"+signature);
        //解密

        String decryptData = AES.decrypt(signature, secret);
        String[] descArr = decryptData.split("&");

        String pwd="";
        for(int i = 0; i < descArr.length; ++i) {
            String keyValue = descArr[i];
            int firstIndex = keyValue.indexOf("=");
             if(keyValue.substring(0, firstIndex).equals("password")) {
                pwd=keyValue.substring(firstIndex + 1);//获取到密码
            }
        }
        System.out.println("解密后的密码:"+pwd);

    }

}




2、2、另一组代码
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AESUtil {
	static String key="finedo_nxcrm_aes";
	static byte[] ivByte = { 85, 60, 12, 116, 99, (byte) (-67 + 256), (byte) (-83 + 256), 19, (byte) (-118 + 256),
		(byte) (-73 + 256), (byte) (-24 + 256), (byte) (-8 + 256), 82, (byte) (-24 + 256), (byte) (-56 + 256),
		(byte) (-14 + 256) };
	//加密
	public static String Encrypt(String src) throws Exception {
		if (key == null) {
			System.out.print("Key为空null");
			return null;
		}
		// 判断Key是否为16位
		if (key.length() != 16) {
			System.out.print("Key长度不是16位");
			return null;
		}
		byte[] raw = key.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec ivps = new IvParameterSpec(ivByte);// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps);
		byte[] encrypted = cipher.doFinal(src.getBytes("UTF-8"));
		//return Base64.encodeBase64String(encrypted);
		return Base64.encodeBase64URLSafeString(encrypted);
	}
	//解密
	public static String Decrypt(String src) throws Exception {
		if (key == null) {
			System.out.print("Key为空null");
			return null;
		}
		if (key.length() != 16) {
			System.out.print("Key长度不是16位");
			return null;
		}
		byte[] raw = key.getBytes("ASCII");
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		IvParameterSpec ivps = new IvParameterSpec(ivByte);
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivps);
		byte[] encrypted1 = Base64.decodeBase64(src.getBytes("utf-8"));
		byte[] original = cipher.doFinal(encrypted1);
		String originalString = new String(original);
		return originalString;	
	}
	//测试
	public static void main(String[] args) throws Exception {
		String src = "sys_9511";
		System.out.println("加密前:" + src);
		String enString = AESUtil.Encrypt(src);
		System.out.println("密文是:" + enString);
		
		String DeString = AESUtil.Decrypt(enString);
		System.out.println("解密后的明文是:" + DeString);	
	}
}

  

 
posted @ 2022-02-15 15:45  梦幻&浮云%  阅读(49)  评论(0编辑  收藏  举报