
一个简单的凯撒密码的命令行加密工具
发布日期:2021-05-07 13:11:26
浏览次数:17
分类:原创文章
本文共 1845 字,大约阅读时间需要 6 分钟。
文章目录
简介
凯撒密码是很经典的一种简单加密方法,可以将字母的位移视作加密的密钥,因为英文字母只有 26 位,所以加密密钥也只有 26 种可能,这使得破解凯撒密码极其容易(最多只需要试 26 次就可以了)。
不过实际应用中我们可以通过扩展加密文本的范围来使密钥的可能性增多,比如在 char
的范围上位移。
本文所给出的代码还实现了负位移的加密,不过密钥的可能性还是只有 26 位,因为同余的密钥加密结果相同。
使用方法
例如:
./caesar_code "Hello World! 233" -23
输出:
Khoor Zruog! 233
源代码
/* * Useage: caesar_code <string for code> [shift for code (default is 0)] * * Effect: output a string which is coded by Caesar Code * * Note: this program only make shift on alphabet character */#include <iostream>using namespace std;inline char code(char ch, int shift) { shift = ((shift % 26) + 26) % 26; // in case of negative shift and overflow if (isupper(ch)) { return 'A' + (ch - 'A' + shift) % 26; } else if (islower(ch)) { return 'a' + (ch - 'a' + shift) % 26; } else { return ch; }}string code(const string &s, int shift) { string ret = s; shift %= 26; // in case of overflow shift = (shift + 26) % 26; // in case of negetive shift cout << "equivalent shift = " << shift << endl; // use anonymous function to avoid redundant % 26 operation // maybe you could use a private function _safe_code instead auto code = [&](char ch) { if (isupper(ch)) { return char('A' + (ch - 'A' + shift) % 26); } else if (islower(ch)) { return char('a' + (ch - 'a' + shift) % 26); } else { return ch; } }; for (auto &ch : ret) { ch = code(ch); } return ret;}int main(const int argc, const char *argv[]) { const string &s = argv[1]; const int shift = stoi(argv[2]); cout << code(s, shift) << endl; }
Makefile
caesar_code : caesar_code.cc g++ caesar_code.cc -o caesar_code# run : caesar_code# ./caesar_codetest : caesar_code ./caesar_code 'Hello World! 233' -23clean : rm caesar_code
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2025年03月28日 23时01分42秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
C++并发与多线程(一)
2019-03-04
C++ 并发与多线程(五)
2019-03-04
STM32--USART串口收发数据
2019-03-04
7628 EDCCA认证寄存器修改(认证自适应)
2019-03-04
C#四行代码写简易计算器,超详细带注释(建议新手看)
2019-03-04
计算机网络子网划分错题集
2019-03-04
java一些基本程序
2019-03-04
数据结构经典十套卷之八
2019-03-04
tensorflow入门变量常量
2019-03-04
卷积神经网络六之CNN反向传播计算过程
2019-03-04
神经元与神经网络一之概述
2019-03-04
神经网络二之手写数字识别
2019-03-04
神经网络六之反向传播
2019-03-04
第五章 数字滤波器的基本结构之三
2019-03-04
FANUC机器人R-30iB_R-30iB PLUS备件规格型号统计整理
2019-03-04
FANUC机器人的镜像备份操作及U盘格式化具体步骤
2019-03-04
vue-依赖-点击复制
2019-03-04
js井子棋
2019-03-04
css取消双击选中文字
2019-03-04
LeetCode 116填充每个节点的下一个右侧结点指针
2019-03-04