gpt4 book ai didi

c++ - 修改程序以加密大写和小写输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:19:39 24 4
gpt4 key购买 nike

我必须为随 secret 码问题编写代码。我已经做到了,但是程序只转换大写或小写(取决于我选择的)字母作为输入。我应该更改什么才能使程序同时转换大写和小写字母?

代码:

   srand(time(0));     //seed for rand()
static char alphabet[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string alph="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int LENGTH=sizeof(alphabet)-1;

int r;
char temp;
for (unsigned int i=0; i<LENGTH; i++) //loop which shuffles the array
{
r=rand() % LENGTH;
temp=alphabet[i];
alphabet[i] = alphabet[r];
alphabet[r]=temp;
}

string text;
getline (cin, text);
for (unsigned int i=0; i<text.length(); i++) //loop to encrypt
{
if (isalpha(text[i]))
{
text[i]=alphabet[text[i] - 'A']; //index alphabet with the value of text[i], adjusted to be in the range 0-25

}
}

最佳答案

编辑:添加了完整代码(也用于解密此替代密码)

添加小写字符的第二个字母表并在同一个循环中修改它,该循环打乱第一个字母表的数组,如:

temp=alphabet_of_lowerCase[i];         
alphabet_of_lowerCase[i] = alphabet_of_lowerCase[r];
alphabet_of_lowerCase[r]=temp;

现在在你的加密方案中,只需检查符号是小写字母还是大写字母,islower is isupper 函数,并在 isalpha 中相应地使用所需的字母表数组> 如果分支:

if (islower()) {
text[i]= alphabet_of_lowerCase[text[i] - 'a'];
}
else
// your previous code

完整代码:

static char alphabet[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char text[] = "TEST";

void shuffleAlphabet() {

srand(time(0)); //seed for rand()

const int LENGTH = sizeof(alphabet)-1;

int r;
char temp;
for (unsigned int i=0; i<LENGTH; i++) //loop which shuffles the array
{
r=rand() % LENGTH;
temp=alphabet[i];
alphabet[i] = alphabet[r];
alphabet[r]=temp;
}

}

void cipher(int decrypt) {

for (unsigned int i=0; i<strlen(text); i++) //loop to encrypt
{
if (isalpha(text[i]))
{
if (!decrypt)
text[i]=alphabet[text[i] - 'A']; //index alphabet with the value of text[i], adjusted to be in the range 0-25
else {
int charPos = strchr(alphabet, text[i]) - alphabet; // calculate character position in cipher alphabet
text[i]='A' + charPos; // and advance forward in standard alphabet by this position
}
}
}

}

int main()
{
printf("Text: %s\n", text);
shuffleAlphabet();
printf("Cipher alphabet: %s\n", alphabet);
cipher(0);
printf("Encrypted: %s\n", text);
cipher(1);
printf("Decrypted: %s\n", text);

return 0;
}

所以一般来说,您只需要知道用于解密加密文本的密码字母表即可。实际上你甚至不必知道密码字母表解码加密文本,因为你可以使用 frequency analysis用于破解几乎所有替代密码(包括 XOR 加密)。除非 ... 替换密码中使用的 key 与原始文本的长度相同并且始终是随机的,- 在这种情况下我们将获得牢不可破的 one-time pad .

关于c++ - 修改程序以加密大写和小写输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28281094/

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