package tool import ( "strings" ) func MaskJWT(token string) string { if token == "" { return "" } parts := strings.Split(token, ".") if len(parts) != 3 { return MaskString(token, 5, 5, -1, "*") } h, p, s := parts[0], parts[1], parts[2] h, p, s = MaskString(h, 5, 5, 8, "*"), MaskString(p, 5, 5, 8, "*"), MaskString(s, 5, 5, 8, "*") return h + "." + p + "." + s } // MaskString 将字符串中间部分替换为 maskChar // // start: 保留前 start 个字符 // end: 保留后 end 个字符 // maskLen: 中间打码长度 (小于 0 标识保持原有长度) // maskChar: 打码字符 func MaskString(s string, start, end, maskLen int, maskChar string) string { if s == "" { return "" } totalLen := len(s) if start < 0 { start = 0 } if end < 0 { end = 0 } if maskChar == "" { maskChar = "*" } maxMaskLen := totalLen - start - end if maxMaskLen <= 0 { return strings.Repeat(maskChar, totalLen) } if maskLen < 0 || maskLen > maxMaskLen { maskLen = maxMaskLen } startPart, endPart := s[:start], s[totalLen-end:] return startPart + strings.Repeat(maskChar, maskLen) + endPart }