一个简单的凯撒密码的命令行加密工具
发布日期: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
上一篇:长沙理工大学 GPA 自动计算爬虫
下一篇:CSUST 2021 周赛 2 题解

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年03月28日 23时01分42秒