liujie
2026-07-10 bedff910eb2394a8ce68762a8f3a413d81187ac1
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
package com.ruoyi.system.utils;
 
import com.ruoyi.common.exception.ServiceException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
 
/**
 * 员工手机号加密工具
 *
 * @author ruoyi
 */
public class EmployeePhoneCrypto
{
    private static final String SECRET = "FangKeJiEmployeePhoneKey20260707";
 
    private static final SecureRandom SECURE_RANDOM = new SecureRandom();
 
    private EmployeePhoneCrypto()
    {
    }
 
    public static String encrypt(String plainText)
    {
        try
        {
            byte[] iv = new byte[16];
            SECURE_RANDOM.nextBytes(iv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey(), new IvParameterSpec(iv));
            byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            byte[] merged = new byte[iv.length + encrypted.length];
            System.arraycopy(iv, 0, merged, 0, iv.length);
            System.arraycopy(encrypted, 0, merged, iv.length, encrypted.length);
            return Base64.getEncoder().encodeToString(merged);
        }
        catch (Exception e)
        {
            throw new ServiceException("手机号加密失败");
        }
    }
 
    public static String decrypt(String cipherText)
    {
        if (cipherText == null || cipherText.length() == 0)
        {
            return "";
        }
        try
        {
            byte[] merged = Base64.getDecoder().decode(cipherText);
            byte[] iv = Arrays.copyOfRange(merged, 0, 16);
            byte[] encrypted = Arrays.copyOfRange(merged, 16, merged.length);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey(), new IvParameterSpec(iv));
            return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8);
        }
        catch (Exception e)
        {
            throw new ServiceException("手机号解密失败");
        }
    }
 
    public static String hash(String phone)
    {
        return Hex.encodeHexString(DigestUtils.sha256(normalize(phone)));
    }
 
    public static String normalize(String phone)
    {
        return phone == null ? "" : phone.trim();
    }
 
    private static SecretKeySpec secretKey()
    {
        byte[] keyBytes = DigestUtils.sha256(SECRET);
        return new SecretKeySpec(Arrays.copyOf(keyBytes, 16), "AES");
    }
}