一个简单的凯撒密码的命令行加密工具

本文介绍了凯撒密码的加密原理,这是一种简单的字母位移加密方法。虽然易破解,但可通过扩展字符范围增加安全性。代码示例展示了如何实现包括负位移在内的加密,并提供了使用方法和源代码。此外,还包含了一个Makefile用于编译和运行程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

凯撒密码是很经典的一种简单加密方法,可以将字母的位移视作加密的密钥,因为英文字母只有 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_code

test : caesar_code
	./caesar_code 'Hello World! 233' -23

clean :
	rm caesar_code
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值