Files
bl/common/utils/go-sensitive-word-1.3.3/docs/zero-width.md
昔念 685069fded feat(cool): 添加敏感词过滤功能
- 引入 go-sensitive-word 敏感词过滤库
- 在全局初始化中加载敏感词库并配置过滤器
- 在创建玩家时应用敏感词过滤,替换不合适的昵称内容
2025-09-09 01:11:10 +08:00

56 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 零宽字符攻击
在Go语言中防止零宽字符攻击可以通过一些方法来实现零宽字符攻击通常是通过在字符串中插入隐藏的零宽字符来欺骗系统例如在认证字符串中插入零宽空格来绕过验证等以下是一些防止零宽字符攻击的方法
- 验证输入字符串在接受用户输入的地方进行输入验证确保字符串中不包含任何不必要的或可疑的字符可以使用正则表达式或简单的字符检查来过滤或拒绝包含零宽字符的字符串
- 规范化字符串在处理输入字符串之前可以使用Unicode规范化函数将字符串标准化为特定形式以移除任何不必要的或隐藏的字符
- 使用字节处理而不是字符串在某些情况下将字符串视为字节序列可能更安全通过将字符串转换为字节切片并以字节为单位进行处理可以避免字符串中的隐藏字符问题
```go
// IsZeroWidth 是否存在零宽字符
func IsZeroWidth(s string) bool {
re := regexp.MustCompile(`[\p{Cf}\\u200B]`)
return re.MatchString(s)
}
// RemoveZeroWidth 移除零宽字符
func RemoveZeroWidth(s string) string {
re := regexp.MustCompile(`[\p{Cf}\\u200B]`)
return re.ReplaceAllString(s, "")
}
```
```go
import (
"fmt"
"testing"
)
const (
str1 = "马斯克"
str2Zero = "马​‌‍斯​‌‍克​‌‍"
str3Zero = "马\\u200B斯\\u200B克"
)
func TestIsZeroWidth(t *testing.T) {
res1 := IsZeroWidth(str1)
fmt.Println("res1 结果:", res1) // false
res2 := IsZeroWidth(str2Zero)
fmt.Println("res2 结果:", res2) // true
res3 := IsZeroWidth(str3Zero)
fmt.Println("res3 结果:", res3) // true
}
func TestRemoveIsZeroWidth(t *testing.T) {
res1 := RemoveZeroWidth(str1)
fmt.Println("res1 结果:", res1) // 马斯克
res2 := RemoveZeroWidth(str3Zero)
fmt.Println("res2 结果:", res2) // 马斯克
res3 := res1 == res2
fmt.Println("res1 和 res2 比较的结果:", res3)
}
```