Golang 实现凯撒密码

栏目: Go · 发布时间: 7年前

一.凯撒密码加密代码思路

基本思路:

  1. 设置明文 和 位移步长(秘钥)
  2. 将明文转成小写,准备 明文字节切片 与 密文切片
  3. 循环将每个明文字符 按照 位移步长 做位移,存入密文切片
  4. 返回密文

Golang 实现凯撒密码

  • 导入包
import (
    "fmt"
    "strings" // 包含字符串操作相关方法
)
  • 凯撒密码加密代码
//一、凯撒密码加密
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("明文字符切片:", 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("加密结果为:", step_move, str_slice_dst, string(str_slice_dst))
    return string(str_slice_dst)
}

二.凯撒密码解密代码思路

基本思路:

  1. 设置密文 和 位移步长
  2. 准备 密文字符切片 与 明文字符切片
  3. 循环将每个 密文字符 按照位移步长 做位移,存入明文切片
  4. 返回明文

Golang 实现凯撒密码

  • 凯撒密码解密代码
//二、凯撒密码解密
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("密文字符切片:", 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.输出结果
    fmt.Println("解密结果为:", step_move, str_slice_dst, string(str_slice_dst))
    return string(str_slice_dst)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Shallows

The Shallows

Nicholas Carr / W. W. Norton & Company / 2010-6-15 / USD 26.95

"Is Google making us stupid?" When Nicholas Carr posed that question, in a celebrated Atlantic Monthly cover story, he tapped into a well of anxiety about how the Internet is changing us. He also crys......一起来看看 《The Shallows》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具