c++ - 为什么这个微小的 RSA 实现会给出错误的结果?

标签 c++ c encryption cryptography rsa

我正在尝试实现一个简单的 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,不是吗?

我到底哪里出错了?

[编辑]

我对 d 的计算是否正确?

最佳答案

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

关于c++ - 为什么这个微小的 RSA 实现会给出错误的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6294060/

相关文章:

c - C 中的斐波那契数对于 1 - 18 非常有效,但 19 根本不起作用

c# - 尝试使用 Python 从工作 C# 代码生成 RSA 签名

C++ 将一个对象设置为默认参数(这是一个引用)

c++ - 在 C++ 中按空格拆分字符串的最快方法

c++ - 无论如何在 C++ 中将 2 维数组煮沸为整数?

mysql - 在生成电子邮件时解密 MySQL 密码以通知用户密码

java - 使用 Java 在 ColdFusion 中计算 HMAC-SHA256 摘要

c++ - 主线程的销毁顺序及pthread_key_create的使用

c++ - 蹩脚的 wav 到数组,然后用 c/c++ 返回 wav

c - 使用指向字符串的指针数组将字符串中的子字符串替换为c中的另一个子字符串