c++ - 加密数字 C++

标签 c++ encryption decimal

所以我试图通过将数字加七然后将整个数字除以十来加密一个四位整数。在我的程序中,我分别取每个数字,然后我需要将整个数字除以十。如何将所有单独的 int 组合成一个四位数?

#include "stdafx.h"
using namespace std;

int main()
{
    //Define all variables needed
    int a,b,c,d,enc,ext;

    //Print dialog and input each single digit for the four number digit
    cout << "Enter Your First Digit:" << endl;
    cin >> a;
    cout << "Enter Your Second Digit:" << endl;
    cin >> b;
    cout << "Enter Your Third Digit:" << endl;
    cin >> c;
    cout << "Enter Your Fourth Digit:" << endl;
    cin >> d;
    //Add seven to each digit
    a += 7;
    b += 7;
    c += 7;
    d += 7;

    a /= 10;
    b /= 10;
    c /= 10;
    d /= 10;

    cout << "Your encrpyted digits:" << c << d << a << b <<endl;

    cout << "Enter 1 to exit:" <<endl;
    cin >> ext;

    if (ext = 1) {
        exit(EXIT_SUCCESS);
    }
}

您可能已经注意到,我将每个数字分开划分。我需要一起做。然后我还创建了一个解密,我将在一个单独的程序中恢复到原始数字。

最佳答案

根据您的评论,您正在尝试对 Caesar Cipher 进行修改,在这种情况下,您应该使用取模运算符 (%) 而不是整数除法运算符 (/)。使用整数除法会丢失信息,这将阻止您解密。当您的数字在 {0, 1, 2} 中时,您的除法结果为 0。当它在 {3, 4, 5, 6, 7, 8, 9} 中时,除法结果为 1。您不能将 {0, 1} 解密回原始数字,无需一些附加信息(您已丢弃)。

如果您想使用凯撒密码方法逐位加密,您应该使用 modulo arithmetic这样每个数字都有一个唯一的加密值,可以在解密过程中检索到。如果这确实是您要查找的内容,那么您应该执行类似以下操作以使用 7 进行加密:

    a = (a + 7) % 10;
    b = (b + 7) % 10;
    c = (c + 7) % 10;
    d = (d + 7) % 10;

要解密,您减去 7,在 mod 10 算术中是 3 的加法,因此将是:

    a = (a + 3) % 10;
    b = (b + 3) % 10;
    c = (c + 3) % 10;
    d = (d + 3) % 10;

当然,这假定您已经正确验证了您的输入(在上面的示例中不是这种情况)。

关于c++ - 加密数字 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7778573/

相关文章:

c++ - 在 C++ 中使用 Cstrings 反转字符串

c++ - 使用 std::tie 比较结构

python - 为什么 "decimal.Decimal(' 0') < 1.0"在 Python 2.6.5 中产生 False

c++ - "How to make a recursive call for palindrom numbers without reverse function in c++?"

c++ - 有没有比 qsort 更快的排序程序?

python - App Engine python 上用于 PayPal 网络支付标准的加密 PayPal 按钮?

node.js - 使用 OpenPGP.js 解密非装甲 PGP 文件

c++ - 可以从 ByteQueue 中抽取数据的自定义源

python - 有什么办法可以让整数被归类为没有 .0 的整数,而 float 被归类为 float 吗?

Java将负二进制转换回整数