无关风月
2026-01-13 d98af68f2ea108254ec362ac2497fd619e6dd3eb
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
package com.ruoyi.system.utils.xiMaUtil;
 
 
import org.bouncycastle.jce.provider.BouncyCastleProvider;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
 
/**
 * 
 * 加密方式:AES CBC模式 
 * Key:ciicciicciicciic
 * IV:ciic2022ciic2022
 * 例:
 * 加密前:1234567890
 * 加密后:10ed567b9d42a385926d6166f97008ce
 * 
 * 测试地址参考:http://tool.chacuo.net/cryptaes/
 * AES加密模式:CBC  填充:pkcs7padding  数据块:128位 密码:ciicciicciicciic 偏移量:ciic2022ciic2022  输出:hex 字符集:utf8编码(unicode编码)
 * 
 */
public class AesUtil {
 
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
 
    public static void main(String[] args) {
        try {
            //根据指定字符串生成秘钥
            /*KeyGenerator kg = KeyGenerator.getInstance("AES");
            kg.init(128,new SecureRandom("ceshi".getBytes()));
            SecretKey sk = kg.generateKey();
            String keyStr = Base64.getEncoder().encodeToString(sk.getEncoded());
            byte[] iv = Base64.getDecoder().decode(keyStr);
            byte[] key = Base64.getDecoder().decode(keyStr); */
 
            String key = "7bc47ce80ff74c1cbebad1ced111243d";
            String iv = "69b84732eace4e6a";
            String content = "1234567890";
            String encrypted = encrypt(key, iv,  content);
            System.out.println("加密后: " + encrypted);
 
            String raw = decrypt(key, iv , encrypted);
            System.out.println("解密后: " + raw);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static String encrypt(String key, String iv,  String content) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");//"算法/模式/补码方式"
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
            return Hex.byteToHex(cipher.doFinal(content.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
 
    public static String decrypt(String key,String iv, String content) {
 
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
            return new String(cipher.doFinal(Hex.hexToByte(content)) );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
}