当前位置:网站首页>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.Map
1 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
exxegoexsrgi
strings.Map
2.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 attackatonce
6 summary
边栏推荐
- 图解网络:什么是热备份路由器协议HSRP?
- Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
- GUI Graphical user interface programming (XIV) optionmenu - what do you want your girlfriend to wear on Valentine's day
- What kind of experience is it when the Institute earns 20000 yuan a month!
- 选择排序与冒泡排序模板
- Mitsubishi M70 macro variable reading Mitsubishi M80 public variable acquisition Mitsubishi CNC variable reading acquisition Mitsubishi CNC remote tool compensation Mitsubishi machine tool online tool
- Redis notes (I) Linux installation process of redis
- JDBC 进阶
- Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
- CesiumJS 2022^ 源码解读[0] - 文章目录与源码工程结构
猜你喜欢
图解网络:什么是热备份路由器协议HSRP?
Teach you how to optimize SQL
pytest多进程/多线程执行测试用例
What are the virtual machine software? What are their respective functions?
Redis notes (I) Linux installation process of redis
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
Leetcode51.n queen
What is the difference between enterprise wechat applet and wechat applet
Management and thesis of job management system based on SSM
ctf-pikachu-CSRF
随机推荐
[PaddleSeg 源码阅读] PaddleSeg 自定义数据类
Teach you how to optimize SQL
Zigzag scan
2022-07-03:数组里有0和1,一定要翻转一个区间,翻转:0变1,1变0。 请问翻转后可以使得1的个数最多是多少? 来自小红书。3.13笔试。
Add token validation in swagger
Class summation, shortest row
MySQL backup notes
[paddleseg source code reading] paddleseg calculation dice
AAAI2022 | Word Embeddings via Causal Inference: Gender Bias Reducing and Semantic Information Preserving
Select sorting and bubble sorting template
用于TCP协议交互的TCPClientDemo
'2'&gt;' 10'==true? How does JS perform implicit type conversion?
[paddleseg source code reading] normalize operation of paddleseg transform
选择排序与冒泡排序模板
logistic regression
Es network layer
Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure
Leecode 122. Zuijia timing of buying and selling stocks ②
How to pipe several commands in Go?
JDBC 进阶