当前位置:网站首页>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 总结
边栏推荐
- (column 23) typical C language problem: find the minimum common multiple and maximum common divisor of two numbers. (two solutions)
- Objective-C member variable permissions
- [paddleseg source code reading] paddleseg calculates Miou
- 機器學習基礎:用 Lasso 做特征選擇
- Exercices de renforcement des déclarations SQL (MySQL 8.0 par exemple)
- 深入浅出对话系统——使用Transformer进行文本分类
- Detailed explanation of PPTC self recovery fuse
- 渗透实战-SQLServer提权
- Objective-C description method and type method
- Recent learning fragmentation (14)
猜你喜欢

What is cloud primordial?
![[latex] production of complex tables: excel2latex and detail adjustment](/img/39/0d448ddf006eda262de3ed75666354.jpg)
[latex] production of complex tables: excel2latex and detail adjustment

Mindmanager2022 efficient and easy to use office mind map MindManager

How to use websocket to realize simple chat function in C #
![Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]](/img/0d/7a8370d153a8479b706377c3487220.jpg)
Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]

functools下的reduce函数

logistic regression

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

Want to do something in production? Then try these redis commands

JSON string conversion in unity
随机推荐
MySQL backup notes
Sword finger offer:55 - I. depth of binary tree
[untitled]
The property of judging odd or even numbers about XOR.
In my spare time, I like to write some technical blogs and read some useless books. If you want to read more of my original articles, you can follow my personal wechat official account up technology c
PMP 考試常見工具與技術點總結
Audio and video technology development weekly | 232
機器學習基礎:用 Lasso 做特征選擇
Katalon框架测试web(二十一)获取元素属性断言
1day vulnerability pushback skills practice (3)
【.NET+MQTT】.NET6 環境下實現MQTT通信,以及服務端、客戶端的雙邊消息訂閱與發布的代碼演示
[database I] database overview, common commands, view the table structure of 'demo data', simple query, condition query, sorting data, data processing function (single row processing function), groupi
super_ Subclass object memory structure_ Inheritance tree traceability
JS object definition
智慧地铁| 云计算为城市地铁交通注入智慧
Wechat official account web page authorization
Jenkins continuous integration environment construction V (Jenkins common construction triggers)
Monitoring - Prometheus introduction
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches