gpt4 book ai didi

c - 如何在 C 中加密文本?

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:30 25 4
gpt4 key购买 nike

我正在解决一个问题,我有点卡住了,所以我想寻求你的帮助。我想制作一个具有以下功能的程序。用户将提供一个 4 位密码 key 和一个文本。

然后将使用以下方法将文本转换为密码。假设文本输入为“ABC”, key 为 123。然后,使用 ASCII 表将“ABC”转换为“BDF”。文本将在 ASCII 表中向前移动 K 个位置,其中 K 是键的相应数字。考虑文本无限。我的第一个 Action 是将键转换为数组。

//scanning the cypher key
scanf("%d", &cypherkey);

//converting the cypher key into an array using a practical mathematic method for extracting its digit
int keyarray[4];
keyarray[0]= cypherkey/1000;
keyarray[1]= (cypherkey-keyarray[0]*1000)/100;
keyarray[2]= ((cypherkey-keyarray[0]*1000)- keyarray[1]*100)/10;
keyarray[3]= ((cypherkey-keyarray[0]*1000)- keyarray[1]*100)-keyarray[2]*10;

所以,现在我有了数组中的键。但是,我找不到阅读文本然后对其进行加密的好方法。我不能使用数组,因为我们不知道文本的长度。

如有任何帮助,我将不胜感激!

最佳答案

我试了一下,输入的文本是硬编码在应用程序中的。下面的示例不是生产代码,它仅用于教育目的。

在我的方法中有 2 个挑战:

  • 编写计算数字中有多少位的函数:

  • 实现检索数字的特定数字的功能;

.

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

int count_digits(int number) // // http://stackoverflow.com/questions/1489830/efficient-way-to-determine-number-of-digits-in-an-integer
{
int digits = 0;
if (number < 0)
digits = 1;

while (number)
{
number /= 10;
digits++;
}

return digits;
}

char get_digit(int number, int index) // starts at index 0
{
if (number == 0)
return (char)0;

int n_digits = count_digits(number);
if (index > n_digits)
return (char)-1;

char digit = -1;
int i;
for (i = 0; i < (n_digits-index); i++)
{
digit = number % 10;
number /= 10;
}

return digit;
}

int main()
{
printf("* Type the encoding key (numbers only): ");
int key = 0;
scanf("%d", &key);

int key_digits = count_digits(key);
//printf("* The key has %d digits.\n", key_digits);

char input_msg[] = "ABCABC"; // This is the input text
int input_sz = strlen(input_msg);
//printf("* Input message [%s] has %d characters.\n", input_msg, input_sz);

int i, d = 0;
for (i = 0; i < input_sz; i++)
{
if (d >= key_digits)
d = 0;

input_msg[i] += get_digit(key, d);
d++;
}

printf("* Encoded text is: %s\n", input_msg);

return 0;
}

输出以下...

对于输入文本ABC:

$ ./cypher 
* Type the encoding key (numbers only): 123
* Encoded text is: BDF

$ ./cypher
* Type the encoding key (numbers only): 234
* Encoded text is: CEG

对于输入文本ABCABC:

$ ./cypher 
* Type the encoding key (numbers only): 123
* Encoded text is: BDFBDF

关于c - 如何在 C 中加密文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9948839/

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