AES加密解密

AES.java类代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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测试类代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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);
 
    }
 
}
1
22、另一组代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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); 
    }
}

  

1
  
posted @   梦幻&浮云%  阅读(58)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示