desens.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package util
  4. import (
  5. "fmt"
  6. "strings"
  7. "unicode/utf8"
  8. )
  9. // DesensVin 使vin脱敏, Desens => Desensitize
  10. // 输入:vin 车辆唯一编号
  11. // 输出:脱敏后结果,如:LSVGJ4559C2053325 => LSVGJ45*******325
  12. func DesensVin(vin string) string {
  13. if len(vin) != 17 {
  14. return ""
  15. }
  16. return string([]rune(vin)[0:8]) + strings.Repeat("*", 7) + string([]rune(vin)[15:])
  17. }
  18. // DesensName 使姓名脱敏, Desens => Desensitize
  19. // 输入:name 姓名
  20. // 输出:脱敏后结果,如:张三 => 张*, 王老五 => 王*五, 王五杰克 => 王**克
  21. func DesensName(name string) string {
  22. nameRune := []rune(name)
  23. len := utf8.RuneCountInString(name)
  24. switch {
  25. case len == 1:
  26. return name
  27. case len == 2:
  28. return fmt.Sprintf("%s*", string(nameRune[:1]))
  29. case len <= 0:
  30. return "*"
  31. case len > 2:
  32. return fmt.Sprintf("%s%s%s", string(nameRune[:1]), strings.Repeat("*", len-2), string(nameRune[len-1:]))
  33. }
  34. return ""
  35. }
  36. // DesensIdCert 使身份证号码脱敏, Desens => Desensitize
  37. // 输入:idcert 身份证号码
  38. // 输出:脱敏后结果,如:32312219990101342x => 3231**********342x
  39. func DesensIdCert(idcert string) string {
  40. if !IsIdCert(idcert) {
  41. return "*"
  42. }
  43. return fmt.Sprintf("%s%s%s", idcert[:4], strings.Repeat("*", 10), idcert[14:])
  44. }
  45. // DesensIdCert 使手机号码脱敏, Desens => Desensitize
  46. // 输入:idcert 手机号码
  47. // 输出:脱敏后结果,如:18180888088=> 1818****088
  48. func DesensPhone(phone string) string {
  49. // 少于11位或已经包含了*,原样返回
  50. if len(phone) < 11 || strings.Contains(phone, "*") {
  51. return phone
  52. }
  53. return fmt.Sprintf("%s****%s", phone[:3], phone[7:])
  54. }