以下代码为加密解密工具类:
public class MobileNumberUtils { // 密钥,必须为16字节 private static final String AES_KEY = "0123456789abcdef"; /** * 加密手机号 * * @param phoneNumber * @return */ public static String encrypt(String phoneNumber) { try { if (phoneNumber == null || phoneNumber.length() != 11) { throw new IllegalArgumentException("电话号码无效"); } Cipher cipher = Cipher.getInstance("AES"); SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encryptedBytes = cipher.doFinal(phoneNumber.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 解密手机号 * * @param encryptedPhoneNumber * @return */ public static String decrypt(String encryptedPhoneNumber) { try { if (encryptedPhoneNumber == null || encryptedPhoneNumber.isEmpty()) { throw new IllegalArgumentException("加密的电话号码无效"); } Cipher cipher = Cipher.getInstance("AES"); SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPhoneNumber)); return new String(decryptedBytes); } catch (Exception e) { e.printStackTrace(); } return null; } }
运行结果:
public static void main(String[] args) {
String phoneNumber = "18569356552";
String encryptedPhoneNumber = encrypt(phoneNumber);
System.out.println("加密后的手机号:" + encryptedPhoneNumber);
System.out.println("解密后的手机号:" + decrypt(encryptedPhoneNumber));
}