gpt4 book ai didi

c - RSA算法部分字符无法加密(Cryptography)

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:55 25 4
gpt4 key购买 nike

我一直试图在我使用 RSA 算法加密和解密的小代码中解决这个问题,一些字符,如 y、z、x,当我尝试解密它们时返回 'X',以及给出另一个字符的字母像 'f' 给出 'e' 和 'p' 返回 'o'

这是我的代码:

#include <stdio.h>
#include <math.h>

void main()
{
char msg[255];
char crp[255], decrp[255];
int p = 3, q = 11, n = p * q, e = 7, d = 3, addition = 96;
int i = 0, k = 0;

printf("your message: ");
scanf("%s", &msg);

while (msg[i] != '\0')
{
k = pow(msg[i] - addition, e);
crp[i] = k % n + addition;
i++;
}
crp[i] = '\0';
printf("\nyour encrypted msg is: %s", crp);

i = 0;
while (crp[i] != '\0')
{
k = pow(crp[i] - addition, d);
decrp[i] = k % n + addition;
i++;
}

decrp[i] = '\0';
printf("\nyour decrypted msg is: %s", decrp);
}

P.S:我不知道为什么,但如果不添加数字“加法”,即 96 是行不通的,我在一些示例中看到了它,但无法理解。

当我更改 p、q、n、e、d 的值时,尽管我计算得很好,但代码不起作用。

这是整个字母表的输出:

输入:

abcdefghijklmnopqrstuvwxyz

输出:

your encrypted msg is:  a}ipn~|bojklgt{yhfmzu^^^^^
your decrypted msg is: abcdeeghijklmnooqrsttXXXXX

最佳答案

267 的正确值是 8031810176,这对于 32 位整数来说太大了。

我会担心 pow() 的准确性,尽管对于您正在处理的值来说可能没问题。然而,编写一个整数幂函数是相当简单的,所以我用它代替了 <math.h> 中的函数。图书馆。

除了小写字母之外,代码仍然错误处理字符;你应该解决这个问题。它还会生成字母表范围之外的数字——见证示例输出中显示的标点符号:

your plaintext msg is:  abcdefghijklmnopqrstuvwxyz

your encrypted msg is: a}ipn~|bojklgt{yhfmzuvwre

your decrypted msg is: abcdefghijklmnopqrstuvwxyz

请注意,加密消息看起来比输入消息和解密消息短。当运行一个程序,使不可打印的字符在 C 十六进制转义时可见,输出为:

your plaintext msg is:  abcdefghijklmnopqrstuvwxyz

your encrypted msg is: a}ipn~|bojklgt{yhfmzuvwr\x7Fe

your decrypted msg is: abcdefghijklmnopqrstuvwxyz

无论如何,这是您的代码有些固定,并且至少产生小写字母的往返:

#include <inttypes.h>
#include <stdio.h>

static int64_t ipow(int64_t x, int64_t n)
{
int64_t m = x;
int64_t r = 1;
while (n > 0)
{
if (n & 1)
r *= m;
m *= m;
n /= 2;
}
return r;
}

int main(void)
{
char msg[255];
char crp[255], decrp[255];
const int64_t p = 3, q = 11, n = p * q, e = 7, d = 3;
const int addition = 'a' - 1;
int i = 0;
int64_t k = 0;

printf("your message: ");
if (scanf("%s", msg) != 1)
return 1;
printf("\nyour plaintext msg is: %s\n", msg);

for (i = 0; msg[i] != '\0'; i++)
{
k = ipow(msg[i] - addition, e);
crp[i] = k % n + addition;
}
crp[i] = '\0';
printf("\nyour encrypted msg is: %s\n", crp);

for (i = 0; crp[i] != '\0'; i++)
{
k = ipow(crp[i] - addition, d);
decrp[i] = k % n + addition;
}
decrp[i] = '\0';
printf("\nyour decrypted msg is: %s\n", decrp);

return 0;
}

关于c - RSA算法部分字符无法加密(Cryptography),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22427836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com