当前位置:网站首页>Getting started with the go language is simple: go implements the Caesar password
Getting started with the go language is simple: go implements the Caesar password
2022-07-04 03:48:00 【InfoQ】
strings.Map1 Caesar code encryption

design idea
- Set plaintext and move step size ( Secret text )
- Convert clear text to lowercase , Prepare clear text byte slices and ciphertext slices
- Each plaintext character rotates according to the displacement step and is stored in the ciphertext
- Back to ciphertext

2 Go Realization
exxegoexsrgistrings.Map2.1 Import package
import (
"fmt"
"strings" // Include string operation related methods
)2.2 To write caesar Method
caesarEn()// Caesar code encryption
func caesarEn(strRaw string, step byte) string {
//1. Make text lowercase
str_raw := strings.ToLower(strRaw)
//2. Define the step size
step_move := step
//3. Convert a string to a plaintext character slice
str_slice_src := []byte(str_raw)
fmt.Println("Clear text character slice:", str_slice_src)
//4. Create a ciphertext character slice
str_slice_dst := str_slice_src
//5. Loop through text slices
for i := 0; i < len(str_slice_src); i++ {
//6. If the plaintext feature of the current period is within the displacement range , Please add a displacement step directly to save the ciphertext character slice
if str_slice_src[i] < 123-step_move {
str_slice_dst[i] = str_slice_src[i] + step_move
} else { //7. If plaintext characters are out of range , Then add the step length after displacement and subtract 26
str_slice_dst[i] = str_slice_src[i] + step_move - 26
}
}
//8. Output results
fmt.Println("The encryption result is:", step_move, str_slice_dst, string(str_slice_dst))
return string(str_slice_dst)
}3 Caesar password decryption
- Set ciphertext and displacement steps
- Prepare ciphertext character slice and plaintext character slice
- The characters of each ciphertext rotate according to the displacement step , And stored in the plaintext slice
- Return clear text

//2. Caesar password decryption
func caesarDe(strCipher string, step byte) string {
//1. Make text lowercase
str_cipher := strings.ToLower(strCipher)
//2. Alternate step size
step_move := step
//3. Convert a string to a plaintext character slice
str_slice_src := []byte(str_cipher)
fmt.Println("Ciphertext character slice:", str_slice_src)
//4. Create a ciphertext character slice
str_slice_dst := str_slice_src
//5. Loop through character text slices
for i := 0; i < len(str_slice_src); i++ {
//6. If the plaintext feature of the current period is within the displacement range , Please add a displacement step directly to save the ciphertext character slice
if str_slice_src[i] >= 97+step_move {
str_slice_dst[i] = str_slice_src[i] - step_move
} else { //7. If plaintext characters are out of range , Then add 26 Step length after subtracting displacement
str_slice_dst[i] = str_slice_src[i] + 26 - step_move
}
}
//8. Output results
fmt.Println("The decryption result is:", step_move, str_slice_dst, string(str_slice_dst))
return string(str_slice_dst)
}4 Other implementations
package main
import (
"errors"
"fmt"
"reflect"
"regexp"
)
var TBL = []rune("abcdefghijklmnopqrstuvwxyz")
var CLUES = []string{"this", "the", "that"}
var (
ErrLength = errors.New("invalid length")
ErrChar = errors.New("invalid char")
ErrNoClue = errors.New("no clue word")
ErrShift = errors.New("invalid shift value")
)
func Encrypt(in string, sh int) (enc string, err error) {
err = assert(in)
if sh < 0 {
err = ErrShift
}
if err != nil {
return
}
enc = shift(in, sh)
return
}
func Decrypt(in string) (dec string, sh int, err error) {
err = assert(in)
if err != nil {
return
}
var hit bool = false
subin := subStr(in)
for i := 0; i < len(CLUES); i++ {
subclue := subStr(CLUES[i])
for j := 0; j < len(subin)-len(subclue)+1; j++ {
if reflect.DeepEqual(subin[j:j+1], subclue[0:len(subclue)-1]) {
sh = subtract([]rune(in)[j], []rune(CLUES[i])[0])
hit = true
break
}
}
}
if !hit {
err = ErrNoClue
return
}
dec = shift(in, -sh)
return
}
func assert(in string) (err error) {
if regexp.MustCompile(`[^a-z\. \r\n]`).MatchString(in) {
err = ErrChar
} else if len(in) > 80 {
err = ErrLength
}
return
}
func shift(in string, sh int) (out string) {
for _, v := range in {
if v == '.' || v == ' ' || v == '\r' || v == '\n' {
out += string(v)
continue
}
i := indexOf(TBL, v)
len := len(TBL)
var ii int = (i + sh) % len
if ii < 0 {
ii += len
}
if ii > len {
ii -= len
}
out += string(TBL[ii])
}
return
}
func subtract(left rune, right rune) (out int) {
l := indexOf(TBL, left)
r := indexOf(TBL, right)
out = l - r
if out < 0 {
out += len(TBL)
}
return
}
func subStr(in string) []int {
subin := make([]int, 0, 79)
for i := range in {
if i > len(in)-2 {
break
}
subin = append(subin, subtract([]rune(in)[i], []rune(in)[i+1]))
}
// return
return subin
}
func indexOf(target []rune, searchChar rune) int {
for i, v := range target {
if v == searchChar {
return i
}
}
return -1
}
func main() {
in := "xlmw mw xli tmgxyvi xlex m xsso mr xli xvmt."
fmt.Printf("in : '%s'\n", in)
out, sh, err := Decrypt(in)
fmt.Printf("out: '%s'\n", out)
fmt.Printf("sh : %d\n", sh)
fmt.Printf("err: %v\n", err)
}
5 test
package main
import (
"fmt"
"strings"
)
func caesar(r rune, shift int) rune {
// Shift character by specified number of places.
// ... If beyond range, shift backward or forward.
s := int(r) + shift
if s > 'z' {
return rune(s - 26)
} else if s < 'a' {
return rune(s + 26)
}
return rune(s)
}
func main() {
value := "test"
fmt.Println(value)
// Test the caesar method in a func argument to strings.Map.
value2 := strings.Map(func(r rune) rune {
return caesar(r, 18)
}, value)
value3 := strings.Map(func(r rune) rune {
return caesar(r, -18)
}, value2)
fmt.Println(value2, value3)
value4 := strings.Map(func(r rune) rune {
return caesar(r, 1)
}, value)
value5 := strings.Map(func(r rune) rune {
return caesar(r, -1)
}, value4)
fmt.Println(value4, value5)
value = "exxegoexsrgi"
result := strings.Map(func(r rune) rune {
return caesar(r, -4)
}, value)
fmt.Println(value, result)
}
test
lwkl test
uftu test
exxegoexsrgi attackatonce6 summary
边栏推荐
- Jenkins configures IP address access
- PHP database connection succeeded, but data cannot be inserted
- Infiltration practice guest account mimikatz sunflower SQL rights lifting offline decryption
- [source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
- Es network layer
- Which product is better for 2022 annual gold insurance?
- 基于PHP的轻量企业销售管理系统
- Support the first triggered go ticker
- CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构
- Baijia forum the founding of the Eastern Han Dynasty
猜你喜欢

The difference between MCU serial communication and parallel communication and the understanding of UART

MySQL one master multiple slaves + linear replication

Session learning diary 1

Consul of distributed service registration discovery and unified configuration management

JVM family -- monitoring tools

Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
![Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure](/img/ba/c1d40de154344ccc9f2fd1dd4cb12f.png)
Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure

What is the difference between enterprise wechat applet and wechat applet

JVM family -- heap analysis

1289_FreeRTOS中vTaskSuspend()接口实现分析
随机推荐
Objective-C string class, array class
Eh, the log time of MySQL server is less than 8h?
Add token validation in swagger
What are the virtual machine software? What are their respective functions?
Monitoring - Prometheus introduction
What is the difference between enterprise wechat applet and wechat applet
Jenkins configures IP address access
Reduce function under functools
Tcpclientdemo for TCP protocol interaction
[paddleseg source code reading] paddleseg custom data class
深入浅出对话系统——使用Transformer进行文本分类
pytest多进程/多线程执行测试用例
Smart subway | cloud computing injects wisdom into urban subway transportation
Want to do something in production? Then try these redis commands
(practice C language every day) pointer sorting problem
New year's first race, submit bug reward more!
Katalon框架测试web(二十一)获取元素属性断言
Defensive programming skills
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
Summary of Chinese remainder theorem