【问题标题】:Why does this tiny RSA implementation give wrong results?为什么这个微小的 RSA 实现会给出错误的结果?
【发布时间】:2011-09-11 18:01:54
【问题描述】:

我正在尝试实现一个简单的 RSA 加密/解密过程,而且我很确定我的方程式是正确的。尽管加密后似乎没有打印出正确的解密值。有什么想法吗?。

//test program
#include <iostream>
#include <string.h>
#include <math.h>
using namespace std;
int gcd(int a, int b);

int main(){
    char character = 'A'; //character that is to be encrypted


    int p = 7;
    int q = 5;
    int e = 0; // just initializing to 0, assigning actual e value in the 1st for loop 


    int n = p*q;
    int phi = (p-1)*(q-1);
    int d = 0; // " " 2nd for loop

    //---------------------------finding 'e' with phi. where "1 < e < phi(n)"
    for (int i=2; i < phi; i++){
        if (gcd(i,phi) == 1){ //if gcd is 1
            e = i;
            break;
        }
    }
    //----------------------------

    //---------------------------finding 'd' 

    for (int i = 2; i < phi; i++){
        int temp = (e*i)%phi;
        if (temp == 1){
            d = i;
            break;
        }
    }

    printf("n:%d , e:%d , phi:%d , d:%d \n",n,e,phi,d);
    printf("\npublic key is:[%d,%d]\n",e,n);
    printf("private key is:[%d,%d]\n",d,n);

    int m = static_cast<int>(character); //converting to a number
    printf("\nconverted character num:%d\n",m);


    //Encryption part  ie. c = m^e MOD n
    int power = pow(m,e); // m^e
    int c = power%n;      // c = m^e MOD n. ie. encrypted character
    printf("\n\nEncrypted character number:%d\n",c);

    //decryption part,  ie. m = c^d MOD n
    power = pow(c,d);
    int m2 = power%n; 
    printf("\n\ndecrypted character number:%d\n",m2);


    return 0;
}

int gcd(int a, int b){
    int r;
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    if (b > a) { 
        r = b; b = a; a = r;
    }
    while (b > 0) {
        r = a % b;
        a = b;
        b = r;
    }
    return a;
}

(用于测试的素数是 5 和 7)

在这里,我将字符“A”转换为其数值,当然是 65。当我使用 c = m^e MOD n(其中 m 是转换后的值,即 65)加密此值时,它给我的 c 为 25。

现在,为了扭转这个过程,我做m = c^d MOD n,这给了我m 30 ...这真的不正确,因为它应该是65,不是吗?

我到底哪里出错了?

[编辑]

我对@9​​87654325@ 的计算是否正确?

【问题讨论】:

  • 如果'e'不为零,它会起作用吗?
  • int e = 0 只是一个 dummy,e 用第一个 for 循环中要使用的实际 e 值重写
  • @Jay 同样适用于 'int d=0',我只是在开始时将其初始化为 0,以便稍后在第二个 for 循环中分配实际的 'd' 值跨度>
  • 请注意:如果这是用于商业/非私人用途,请不要自己实现加密功能。一些微小的概述造成巨大的安全漏洞的可能性非常大。在这种情况下,我建议查看 OpenSSL 库。

标签: c++ c encryption cryptography rsa


【解决方案1】:

加密消息m 必须小于n。您不能使用大于 n 的值,因为计算是以 n 为模完成的。在你的情况下m=65n=35。所以你实际上得到了以n为模的正确答案,因为65 % 35 == 30

【讨论】:

【解决方案2】:

这是由于 @interjay 已经回答了 m 大于或等于 n 造成的。

但我发现您的代码存在另一个问题,我的 gcc4.1.2 编译器输出 24 的加密值不是 25。这是因为您使用pow() 函数,然后将结果(类型为double)转换为导致精度损失的int。

不要使用pow()函数,而是使用square and multiply modulo n算法计算c = m^e MOD nm = c^d MOD n。它比pow() 快,您不需要不安全地将结果向下转换为整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2012-12-06
    • 2019-02-01
    相关资源
    最近更新 更多