【问题标题】:RSA Algorithm is not working for certain numbersRSA 算法不适用于某些数字
【发布时间】:2022-01-03 14:52:07
【问题描述】:

我有一个家庭作业,包括处理用户登录和注册。为此,老师告诉我们使用 RSA 算法来加密用户的密码。我的问题是 RSA。我正在尝试将其编写为仅加密 1 个整数,然后我将编写一个加密字符串的新方法。 因此,此时,我的代码适用于某些整数,而对于其他整数则失败得很糟糕。 这是头文件

#ifndef _RSA_
#define _RSA_

#include <cmath>
#include <string>

// A class that defines the RSA algorithm
class RSA {
    private:
        int p, q, n, z, d = 0, e;

    public:
        RSA();
        int gcd(int a, int b);
        int encrypt(int m);
        int decrypt(int c);
    
};

#endif

这是我实现这些功能的文件。

#include "./RSA.h"

RSA::RSA() {
    this->p = 3;
    this->q = 11;
    this->z = (this->p - 1) * (this->q - 1);
    this->n = this->p * this->q;

    for (this->e = 2; this->e < this->z; this->e++) {
        if (this->gcd(this->e, this->z) == 1) {
            break;
        }
    }

    for (int i = 0; i <= 9; ++i) {
        int x = (i * this->z) + 1;
        if (x % this->e == 0) {
            this->d = x / this->e;
            break;
        }
    }
}

int RSA::gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

int RSA::encrypt(int m) {
    return (int)pow(m, e) % this->n;
}

int RSA::decrypt(int c) {
    return (int)pow(c, d) % this->n;
}

现在我将为您提供一些有效的数字和一些无效的数字。 说数字有效,我的意思是在我解密加密方法的结果后,我得到了初始数字。 它适用于 1,2,6,7,8,9,10(加密部分返回 10,解密部分返回 10)、11(与 10 相同)、12(与 11 相同)、13、14、15、16 . 我测试了 [1, 17] 范围内的数字,但 3,4,5,17 失败了。它返回这 4 个数字的完全随机数。另外,我在其他数字范围上尝试过,结果是一样的。

【问题讨论】:

  • pow() 可能不是执行此操作的正确工具,您应该找到一种更好的方法来计算整数值的幂。
  • 你能给我一个更好的方法吗?
  • pow() 实际上返回一个小数并转换回整数。所以它可能会遇到舍入错误。可能应该写你自己的pow()
  • 我写了自己的战俘。而且它仍然没有以正确的方式解密。
  • 请创建一个minimal reproducible example,人们可以轻松粘贴并运行它来证明您的问题。最好使用main 函数和一些硬编码的示例数据。

标签: c++ encryption rsa


【解决方案1】:

即使是这样的小数字,也很容易超过 int 的取幂限制。如果您自己制作 pow,则应在每一步后应用模数:

// computes x**y % n
int custom_pow(int x, int y, int n) {
    int res = 1;
    for(;y;y--) {
        res = (res*x) % n;
    }
    return res;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多