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

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

2 Go实现
exxegoexsrgi
strings.Map
2.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 attackatonce
6 总结
边栏推荐
- JSON string conversion in unity
- Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
- Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
- Objective-C description method and type method
- New year's first race, submit bug reward more!
- what does ctrl + d do?
- [development team follows] API specification
- XSS prevention
- Practical multifunctional toolbox wechat applet source code / support traffic master
- Es network layer
猜你喜欢
[latex] production of complex tables: excel2latex and detail adjustment
Recursive structure
Contest3145 - the 37th game of 2021 freshman individual training match_ 1: Origami
ctf-pikachu-CSRF
Mindmanager2022 efficient and easy to use office mind map MindManager
How to use websocket to realize simple chat function in C #
Code Execution Vulnerability - no alphanumeric rce create_ function()
Consul of distributed service registration discovery and unified configuration management
渗透实战-SQLServer提权
Monitoring - Prometheus introduction
随机推荐
Leetcode51.n queen
ctf-pikachu-CSRF
Simple dialogue system -- text classification using transformer
This function has none of DETERMINISTIC, NO SQL..... (you *might* want to use the less safe log_bin_t
渗透实战-guest账户-mimikatz-向日葵-sql提权-离线解密
JSON string conversion in unity
Nbear introduction and use diagram
Formulaire day05
[untitled]
functools下的reduce函数
Handler source code analysis
渗透实战-SQLServer提权
Imperial cms7.5 imitation "D9 download station" software application download website source code
Which product is better for 2022 annual gold insurance?
Objective C attribute keyword
数据库SQL语句汇总,持续更新......
Day05 錶格
Package details_ Four access control characters_ Two details of protected
[PaddleSeg 源码阅读] PaddleSeg计算 mIoU
Class summation, shortest row