自定义密码程序解密功能异常求助:无法将加密数字转回字母
密码学实操程序decrypt()函数故障排查
我正在完成教授布置的密码学实操练习,设计了一套自定义密码程序:encrypt()函数负责将字符串转换为数字,decrypt()函数需将加密后的数字还原为字母。但目前decrypt()功能无法正常工作,例如输入数字75 102 123 106 102 109时,无法得到预期结果'Jeziel'。
现有代码实现
decrypt()函数代码
void decrypt(int numChar[], int random) { int x = 0; char sMessage[21] = {0}; while ( numChar[x] ) { sMessage[x] = numChar[x] - random; x++; } //end loop sMessage[x] = '\0'; printf("\nDecrypted Message is: "); //print the decrypted message while ( sMessage[x] ) { printf("%c", sMessage[x]); x++; } //end loop } //end decrypt function
main()函数代码
char myString[21] = {0}; int decryptnum[21] = {0}; int iSelection = 0; int iRand; srand(time(NULL)); iRand = (rand() % 4) + 1; // random #, 1-4 while ( iSelection != 4 ) { printf("\n\n1\tEncrypt Clear Text\n"); printf("2\tDecrypt Cipher Text\n"); printf("3\tGenerate New Key\n"); printf("4\tQuit\n"); printf("\nSelect a Cryptography Option: "); scanf("%d", &iSelection); switch (iSelection) { case 1: printf("\nEnter one word as clear text to encrypt: "); scanf("%s", myString); encrypt(myString, iRand); break; case 2: printf("\nEnter cipher text to decrypt: "); x = 0; while (scanf("%d", &decryptnum[x]) == 1) { x++; } break; case 3: iRand = (rand() % 4) + 1; // random #, 1-4 printf("\nNew Key Generated\n"); break; } //end switch } //end loop } //end main
encrypt()函数代码
void encrypt(char sMessage[], int random) { int x = 0; int numChar[21] = {0}; while ( sMessage[x] ) { numChar[x]=sMessage[x] + random; x++; } //end loop x = 0; printf("\nEncrypted Message is: "); //print the encrypted message while ( numChar[x] ) { printf("%d ", numChar[x]); x++; } //end loop } //end encrypt function
问题排查与修复
核心问题点
- main函数未调用decrypt():在case 2中读取完解密数字数组
decryptnum后,没有调用decrypt(decryptnum, iRand),导致读取的数据从未被处理。 - decrypt函数打印循环初始化错误:第一个while循环结束后,变量
x已经指向sMessage数组的末尾(即'\0'的位置),第二个打印循环从x开始,永远无法进入循环输出内容。 - 输入验证与密钥一致性:测试输入
75 102 123 106 102 109对应明文Jeziel的ASCII码加1,所以解密时必须确保iRand为1,否则会得到错误结果。
修复后的代码片段
修复后的main函数case 2部分
case 2: printf("\nEnter cipher text to decrypt: "); int x = 0; // 声明变量x,避免未定义 memset(decryptnum, 0, sizeof(decryptnum)); // 清空数组,防止残留旧数据 while (scanf("%d", &decryptnum[x]) == 1 && x < 20) { // 限制数组长度,防止越界 x++; } decrypt(decryptnum, iRand); // 新增调用decrypt函数 break;
修复后的decrypt函数打印部分
sMessage[x] = '\0'; printf("\nDecrypted Message is: "); //print the decrypted message x = 0; // 重置x为0,从数组起始位置开始打印 while ( sMessage[x] ) { printf("%c", sMessage[x]); x++; } //end loop
验证测试
当输入加密数字75 102 123 106 102 109且密钥iRand=1时,修复后的程序会正确输出明文Jeziel。
内容的提问来源于stack exchange,提问作者jusJeme
相关产品推荐
相关产品推荐

