当前位置:网站首页>Go 语言入门很简单:Go 实现凯撒密码
Go 语言入门很简单:Go 实现凯撒密码
2022-07-04 03:40:00 【InfoQ】
strings.Map1 凯撒密码加密

设计思想
- 设置明文和移动步长(秘文)
- 将清晰的文本转换为小写,准备清晰的文本字节切片和密文切片
- 每个明文字符根据位移的步长旋转并存储在密文片中
- 返回密文

2 Go实现
exxegoexsrgistrings.Map2.1 导入包
import (
"fmt"
"strings" // Include string operation related methods
)2.2 编写 caesar 方法
caesarEn()// 凯撒密码加密
func caesarEn(strRaw string, step byte) string {
//1. 将文本转为小写
str_raw := strings.ToLower(strRaw)
//2. 定义步长
step_move := step
//3. 将字符串转换为明文字符切片
str_slice_src := []byte(str_raw)
fmt.Println("Clear text character slice:", str_slice_src)
//4. 创建一个密文字符切片
str_slice_dst := str_slice_src
//5.循环处理文本切片
for i := 0; i < len(str_slice_src); i++ {
//6.如果当前周期的明文特征在位移范围内,请直接添加位移步骤以保存密文字符切片
if str_slice_src[i] < 123-step_move {
str_slice_dst[i] = str_slice_src[i] + step_move
} else { //7. 如果明文字符超出范围,则加上位移后的步长减去 26
str_slice_dst[i] = str_slice_src[i] + step_move - 26
}
}
//8. 输出结果
fmt.Println("The encryption result is:", step_move, str_slice_dst, string(str_slice_dst))
return string(str_slice_dst)
}3 凯撒密码解密
- 设置密文和位移步骤
- 准备密文字符切片和明文字符切片
- 每个密文的字符根据位移步长旋转,并存储在明文切片中
- 返回明文

//2. 凯撒密码解密
func caesarDe(strCipher string, step byte) string {
//1. 将文本转为小写
str_cipher := strings.ToLower(strCipher)
//2. 替代步长
step_move := step
//3. 将字符串转换为明文字符切片
str_slice_src := []byte(str_cipher)
fmt.Println("Ciphertext character slice:", str_slice_src)
//4. 创建一个密文字符切片
str_slice_dst := str_slice_src
//5. 循环处理字符文本切片
for i := 0; i < len(str_slice_src); i++ {
//6. 如果当前周期的明文特征在位移范围内,请直接添加位移步骤以保存密文字符切片
if str_slice_src[i] >= 97+step_move {
str_slice_dst[i] = str_slice_src[i] - step_move
} else { //7. 如果明文字符超出范围,则加上 26 减去位移后的步长
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 其他实现
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 测试
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 总结
边栏推荐
- SQL injection (1) -- determine whether there are SQL injection vulnerabilities
- Zigzag scan
- EV6 helps the product matrix, and Kia is making efforts in the high-end market. The global sales target in 2022 is 3.15 million?
- This function has none of DETERMINISTIC, NO SQL..... (you *might* want to use the less safe log_bin_t
- Leetcode51.n queen
- MySQL one master multiple slaves + linear replication
- SQL語句加强練習(MySQL8.0為例)
- Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
- [source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
- Calculate the odd sum of 1~n (1~100 as an example)
猜你喜欢

What is cloud primordial?

MySQL query

Nbear introduction and use diagram

Katalon框架测试web(二十六)自动发邮件

(column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)

Don't disagree, this is the most powerful "language" of the Internet

functools下的reduce函数

Tsinghua University product: penalty gradient norm improves generalization of deep learning model

@Scheduled scheduled tasks

The difference between MCU serial communication and parallel communication and the understanding of UART
随机推荐
2022 Guangxi provincial safety officer a certificate examination materials and Guangxi provincial safety officer a certificate simulation test questions
Stm32bug [stlink forced update prompt appears in keilmdk, but it cannot be updated]
AAAI2022 | Word Embeddings via Causal Inference: Gender Bias Reducing and Semantic Information Preserving
super_ Subclass object memory structure_ Inheritance tree traceability
Database SQL statement summary, continuous update
Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
system information
What kind of experience is it when the Institute earns 20000 yuan a month!
Calculate the odd sum of 1~n (1~100 as an example)
[paddleseg source code reading] paddleseg custom data class
[paddleseg source code reading] paddleseg calculates Miou
A review of reverse reinforcement learning at Virginia Tech (VT)
The 37 year old programmer was laid off, and he didn't find a job for 120 days. He had no choice but to go to a small company. As a result, he was confused
2022 registration examination for safety production management personnel of fireworks and firecracker production units and examination skills for safety production management personnel of fireworks an
Value transfer communication between components (parent to child, child to parent, brother component to value)
数据库SQL语句汇总,持续更新......
SQL injection (1) -- determine whether there are SQL injection vulnerabilities
PHP database connection succeeded, but data cannot be inserted
Session learning diary 1
潘多拉 IOT 开发板学习(HAL 库)—— 实验6 独立看门狗实验(学习笔记)