1. import sun.applet.Main;
    2. /**
    3. * 通用脱敏工具类
    4. * 可用于:
    5. * 用户名
    6. * 手机号
    7. * 邮箱
    8. * 地址等
    9. */
    10. public class DesensitizationUtil {
    11. private static final int SIZE = 6;
    12. private static final String SYMBOL = "*";
    13. public static void main(String[] args) {
    14. String name = commonDisplay("慕课网");
    15. String mobile = commonDisplay("13900000000");
    16. String mail = commonDisplay("admin@imooc.com");
    17. String address = commonDisplay("北京大运河东路888号");
    18. System.out.println(name);
    19. System.out.println(mobile);
    20. System.out.println(mail);
    21. System.out.println(address);
    22. }
    23. /**
    24. * 通用脱敏方法
    25. * @param value
    26. * @return
    27. */
    28. public static String commonDisplay(String value) {
    29. if (null == value || "".equals(value)) {
    30. return value;
    31. }
    32. int len = value.length();
    33. int pamaone = len / 2;
    34. int pamatwo = pamaone - 1;
    35. int pamathree = len % 2;
    36. StringBuilder stringBuilder = new StringBuilder();
    37. if (len <= 2) {
    38. if (pamathree == 1) {
    39. return SYMBOL;
    40. }
    41. stringBuilder.append(SYMBOL);
    42. stringBuilder.append(value.charAt(len - 1));
    43. } else {
    44. if (pamatwo <= 0) {
    45. stringBuilder.append(value.substring(0, 1));
    46. stringBuilder.append(SYMBOL);
    47. stringBuilder.append(value.substring(len - 1, len));
    48. } else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
    49. int pamafive = (len - SIZE) / 2;
    50. stringBuilder.append(value.substring(0, pamafive));
    51. for (int i = 0; i < SIZE; i++) {
    52. stringBuilder.append(SYMBOL);
    53. }
    54. if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) {
    55. stringBuilder.append(value.substring(len - pamafive, len));
    56. } else {
    57. stringBuilder.append(value.substring(len - (pamafive + 1), len));
    58. }
    59. } else {
    60. int pamafour = len - 2;
    61. stringBuilder.append(value.substring(0, 1));
    62. for (int i = 0; i < pamafour; i++) {
    63. stringBuilder.append(SYMBOL);
    64. }
    65. stringBuilder.append(value.substring(len - 1, len));
    66. }
    67. }
    68. return stringBuilder.toString();
    69. }
    70. }