这是一个带有一些支持函数的程序,用于进行简单的异或加密/解密。
可能有很多困惑的语法 - 尽管它当前编译没有错误 - 我的问题是它没有通过程序,所以我无法真正很好地测试它。
输入加密 key 后按 Enter 键后,终端屏幕变为空白,但程序不会退出。
如果有人想尝试查看它,或者运行它并亲自查看问题,我将保留下面的代码。这将非常有帮助 - 并且信息丰富,谢谢大家。
很抱歉,代码在某些地方缩进得不好 - 当我从编辑器复制和粘贴时,格式不太好,但我试图使其可读。
这是在 Ubuntu shell 的 VIM 编辑器中用 C 语言编写的。(v14.3)。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_BUF 256
unsigned char getBit(unsigned char, int);
unsigned char setBit(unsigned char, int);
unsigned char clearBit(unsigned char, int);
unsigned char skipx(unsigned char, unsigned char);
unsigned char rotr(unsigned char);
int main()
{
char str[8];
unsigned char c[MAX_BUF];
unsigned char key[MAX_BUF];
int choice;
printf("\nYou may:\n");
printf(" (1) Encrypt a message \n");
printf(" (2) Decrypt a message \n");
printf("\n what is your selection: ");
fgets(str, sizeof(str), stdin);
sscanf(str, "%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter plain text to be encrypted: ");
fgets(c, sizeof(c),stdin);
printf("Press enter to continue.");
scanf("%c",c);
//User interface: Ask user for encryption key
printf("\nNow enter your encryption key: ");
fgets(key, sizeof(key),stdin);
printf("Press enter to continue.");
scanf("%c",key);
int inputLen = strlen(c);
int pos;
for(pos = 0; pos < inputLen; pos++ )
{
skipx(c[pos], *key);
}
int pos2;
for(pos2 = 0; pos2 < inputLen; pos++)
{
printf("%c", c[pos2]);
}
break;
case 2://Decrypt message
printf("\nEnter plain text to be decrypted: ");
fgets(c, sizeof(c),stdin);
printf("Press enter to continue.");
scanf("%c",c);
printf("\nNow enter your decryption key: ");
fgets(key, sizeof(key),stdin);
printf("Press enter to continue.");
scanf("%c",key);
for(pos = 0; pos < inputLen; pos++ ){
skipx(c[pos], *key);
}
//Prints the char array, after being XOR encrypted
for(pos2 = 0; pos2 < inputLen; pos++){
printf("%c", c[pos2]);
}
break;
default:
break;
}
return 0;
}
unsigned char skipx(unsigned char c, unsigned char key)
{
int i; //for looping through the 8 positions of the bit
for(i = 7; i > -1; i--) //Loops through byte, this will be the bit index
{
if(getBit(c,i) % 2 != 0) //only if the number isn't even. ->
{
setBit(getBit(c,i)^getBit(key,i-1),i);
rotr(key);//rotate right to update key
}
}
}
unsigned char rotr(unsigned char c)
{
unsigned char c1 = getBit(c,0) << 7;
unsigned char c2 = c >> 1;
return c1^c2;
}
unsigned char getBit(unsigned char c, int n)
{
return (c & (1 << n)) >> n;
}
unsigned char setBit(unsigned char c, int n)
{
return c | (1 << n);
}
unsigned char clearBit(unsigned char c, int n)
{
return c & (~(1 << n));
}
最佳答案
您的问题是由拼写错误引起的
for(pos2 = 0; pos2 < inputLen; pos++)
您递增了错误的变量。应该是
for(pos2 = 0; pos2 < inputLen; pos2++)
我建议你启用-Wall
编译你的代码,你会发现一些有趣的东西,比如:
test.c: In function ‘main’:
test.c:125:4: warning: ‘inputLen’ may be used uninitialized in this function [-Wmaybe-uninitialized]
for(pos = 0; pos < inputLen; pos++ ){
^
但是您的代码有很多错误:它无法执行预期的操作。
关于c - 输入后程序转到空白终端(C 中的异或加密),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33030669/