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");
|
}
|
}
|