github.com/sandwich-go/boost@v1.3.29/xcrypto/algorithm/vigenere/vigenere.go (about) 1 package vigenere 2 3 // Sanitize 剔除无效的字节 4 func Sanitize(key []byte) []byte { 5 if len(key) == 0 { 6 return key 7 } 8 var out = make([]byte, 0, len(key)) 9 for _, v := range key { 10 if 65 <= v && v <= 90 { 11 out = append(out, v) 12 } else if 97 <= v && v <= 122 { 13 out = append(out, v-32) 14 } 15 } 16 return out 17 } 18 19 func encode(a, b byte) byte { 20 return (((a - 'A') + (b - 'A')) % 26) + 'A' 21 } 22 23 func decode(a, b byte) byte { 24 return ((((a - 'A') - (b - 'A')) + 26) % 26) + 'A' 25 } 26 27 // Encrypt 使用 key 进行加密 28 func Encrypt(src []byte, key []byte) []byte { 29 if len(key) == 0 { 30 return src 31 } 32 out := make([]byte, 0, len(src)) 33 for i, v := range src { 34 out = append(out, encode(v, key[i%len(key)])) 35 } 36 return out 37 } 38 39 // Decrypt 使用 key 进行解密 40 func Decrypt(src, key []byte) []byte { 41 if len(key) == 0 { 42 return src 43 } 44 out := make([]byte, 0, len(src)) 45 for i, v := range src { 46 out = append(out, decode(v, key[i%len(key)])) 47 } 48 return out 49 } 50 51 // EncryptAndInplace 使用 key 进行加密,并且替换 src 52 func EncryptAndInplace(src, key []byte) { 53 if len(key) == 0 { 54 return 55 } 56 for i, v := range src { 57 src[i] = encode(v, key[i%len(key)]) 58 } 59 } 60 61 // DecryptAndInplace 使用 key 进行解密,并且替换 src 62 func DecryptAndInplace(src, key []byte) { 63 if len(key) == 0 { 64 return 65 } 66 for i, v := range src { 67 src[i] = decode(v, key[i%len(key)]) 68 } 69 }