c - 使用 RSA 算法加密-字母 'w' ,'x' ,'y' ,'z'

标签 c encryption cryptography rsa

我一直在为 RSA 算法编写代码。它工作得很好,但不幸的是它显示了小“w”、“z”、“x”、“y”的错误答案。

我的加密算法很简单。使用两个不同的质数和“e”,我生成公钥,然后通过生成“d”,我创建私钥。然后使用 BIGMOD(快速求幂)算法,我只需计算模数部分即可加密和解密。这是我的代码:

#include<stdio.h>
#include<string.h>

long long int square(long long int a);
long long int BigMod(int M,int E,int N);
void encrypt(int l,int E,int N);
void decrypt(int E,int N );

int main()
{
    main_RSA();
    return 0;
}

void main_RSA()
{

    int p,q;
    printf("Write two distinct Prime number separated by space:");
    scanf("%d %d",&p,&q);
    int n=p*q;
    int phi=(p-1)*(q-1);
    int e;
    printf("Enter a prime number 'e' as GCD(e,(P-1)*(Q-1)) : ");
    scanf("%d",&e);
    printf("public key( e , n ) : ( %d %d )\n",e,n);
    int d,RES=-1;
    for(d=1;;d++){
        RES=(d*e)%phi;
        if(RES==1)break;
    }
    printf("Private Key( d,n ) : ( %d %d )\n",d,n);
    printf("Please input your string : ");
    char arr[1000000];
    fflush(stdin);
    gets(arr);
    int i;
    FILE *fp=fopen("RSAlog.dll","w");
    fclose(fp);
    for(i=0;arr[i];i++){
        int ASCII=arr[i];
        encrypt(ASCII,e,n);
    }
    printf("\n");
    FILE *fpp=fopen("RSAlog.dll","a");
    fprintf(fp,"-1");
    fclose(fpp);
    decrypt(d,n);
}
long long int BigMod(int b,int p,int m)  //b^p%m=?
{
    if(p==0)return 1;
    else if(p%2==0)return square(BigMod(b,p/2,m))%m;
    else return ((b % m) * BigMod(b,p-1,m)) % m;

}

long long int square(long long a)
{
    return a*a;
}

void encrypt(int m ,int e,int n){
    FILE *fp;
    fp=fopen("RSAlog.dll","a");
    int c=BigMod(m,e,n);
    printf("%d ",c) ;
    fprintf(fp,"%d ",c);
    fclose(fp);
}

void decrypt(int d,int n){
    FILE *fp;
    fp=fopen("RSAlog.dll","r");
    while(1){
        int c;
        fscanf(fp,"%d",&c);
        //printf("%d ",c);
        if(c==-1)break;
        int m=BigMod(c,d,n);
        printf("%c",m);
    }
}

输出:

Write two distinct Prime number separated by space:7 17
Enter a prime number 'e' as GCD(e,(P-1)*(Q-1)) : 5
public key( e , n ) : ( 5 119 )
Private Key( d,n ) : ( 77 119 )
Please input your string : the quick brown fox runs over the lazy dog
114 83 33 2 78 87 56 29 116 2 98 88 76 0 94 2 51 76 1 2 88 87 94 47 2 76 118 33 88 2 114 83 33 2 75 20 5 32 2 53 76 52
the quick bro n fo☺ runs over the la♥☻ dog

有人可以帮我吗?

最佳答案

你的模数m必须足够大。要对所有 256 个 ASCII 值进行编码和解码,它必须至少为 256。

由于您在示例中使用 119,因此 ASCII 代码 119 ('w') 将被视为 0 等。

关于c - 使用 RSA 算法加密-字母 'w' ,'x' ,'y' ,'z',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19136927/

相关文章:

php - 减少 codeigniter 中的加密字符串长度

networking - AES Rijndael 和小/大端?

c - fscanf 导致段错误

java - Java 中的 ECB 和 CBC AES 输出相同

c - 为什么我会收到错误 (C)?

c# - 使用 C#/CSP 在 HSM 中使用不可导出 key 的 RSA 加密

C# 和德尔福。使用 C# 在 Delphi 中读取加密和压缩的 XML

c - 如何正确使用 libsodium 以使其在版本之间兼容?

c - 线程处理

c - 用 C 打印数字模式