-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.go
79 lines (71 loc) · 2.12 KB
/
convert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package addWaterMark
import (
"fmt"
"regexp"
"strconv"
"strings"
)
// how it works? https://medium.com/@umpox/be-careful-what-you-copy-invisibly-inserting-usernames-into-text-with-zero-width-characters-18b4e6f17b66
// textToBinary just type your name,as the watermark.
func textToBinary(username string) string {
binaryStrings := make([]string, len(username))
for i, char := range username {
binaryStrings[i] = fmt.Sprintf("%08s", strconv.FormatInt(int64(int(char)), 2))
}
return strings.Join(binaryStrings, " ")
}
// binaryToZeroWidth Already Add WaterMark.
func binaryToZeroWidth(binary string) string {
var zeroWidthBuilder strings.Builder
for _, binaryNum := range binary {
if binaryNum == '1' {
zeroWidthBuilder.WriteRune('\u200B') // zero-width space
} else if binaryNum == '0' {
zeroWidthBuilder.WriteRune('\u200C') // zero-width non-joiner
} else {
zeroWidthBuilder.WriteRune('\u200D') // zero-width joiner
}
}
return zeroWidthBuilder.String()
}
// zeroWidthToBinary decode to binary code.
func zeroWidthToBinary(encodingMsg string) string {
var binaryBuilder string
for _, char := range encodingMsg {
switch char {
case '\u200B': // zero-width space
binaryBuilder += "1"
case '\u200C': // zero-width non-joiner
binaryBuilder += "0"
default:
binaryBuilder += " " // add single space
}
}
return binaryBuilder
}
func DecodeBinaryWaterMark(str string) string {
binaryArr := strings.Split(str, " ")
textArr := []byte{}
for _, binaryStr := range binaryArr {
binary, err := strconv.ParseInt(binaryStr, 2, 64)
if err != nil {
panic(err)
}
textArr = append(textArr, byte(binary))
}
return string(textArr)
}
func AddWaterMarkToText(s string, watermark string) string {
binaryCode := textToBinary(watermark)
encodingName := binaryToZeroWidth(binaryCode)
EncodingMsg := s[:] + encodingName
return EncodingMsg
}
func GetWaterMark(str string) string {
usernamePattern := `\p{C}+`
re := regexp.MustCompile(usernamePattern)
waterMark := re.FindAllString(str, -1)
BinaryWaterMark := zeroWidthToBinary(waterMark[0])
binarytoText := DecodeBinaryWaterMark(BinaryWaterMark)
return binarytoText
}