1. 程式人生 > >(團隊)維吉尼亞加密

(團隊)維吉尼亞加密

#include <stdio.h>
#include <String.h> 
#define Q 26


void encrypt(int key, char *input, char *output);
void decrypt(int key, char *input, char *output); 


int main()
{
int selection, key;

printf("1:Encryption\n2:Decryption\n0:Quit\n");
scanf("%d", &selection);
while(selection != 0)
{
printf("Please input your key:");
scanf("%d", &key);

char input[100], output[100];
if(selection == 1)
{
printf("Please input words that need encrypting:");
scanf("%s", input);
encrypt(key, input, output);
printf("Result:%s\n", output);
}
else if(selection == 2)
{
printf("Please input words that need decrypting:"); 
scanf("%s", input);
decrypt(key, input, output);
printf("Result:%s\n", output);
}
else
printf("Invalid input! Please try again!\n");


printf("1:Encryption\n2:Decryption\n0:Quit\n");
scanf("%d", &selection);
}

return 0;
}
void encrypt(int key, char *input, char *output)
{
int length = strlen(input);
for(int i =0; i <= length; i++){
/*if((input[i] >= 'A' && input[i] <= 'Z'-key) || (input[i] >= 'a' && input[i] <= 'z'-key))
output[i] = input[i] + key;
else if(input[i] <= 'Z' && input[i] > 'Z'-key)
output[i] = input[i] - ('Z'-key+1) + 'A';
else if(input[i] <= 'z' && input[i] > 'z'-key)
output[i] = input[i] - ('z'-key+1) + 'a';
else 
output[i] = input[i];*/

if(input[i] >= 'A' && input[i] <= 'Z')
{
output[i] = (input[i]-'A'+key) % Q + 'A'; 
}
else if(input[i] >= 'a' && input[i] <= 'z')
{
output[i] = (input[i]-'a'+key) % Q + 'a';
}
else
output[i] = input[i];
}
}


void decrypt(int key, char *input, char *output)
{
int length = strlen(input);
for(int i = 0; i <= length; i++){
/*if((input[i] >= 'A'+key && input[i] <= 'Z') || (input[i] >= 'a'+key && input[i] <= 'z'))
output[i] = input[i] - key;
else if(input[i] < 'A'+key && input[i] >= 'A')
output[i] = input[i] + ('Z'-key+1) - 'A';
else if(input[i] <= 'z' && input[i] > 'z'-key)
output[i] = input[i] + ('z'-key+1) - 'a';
else 
output[i] = input[i];*/
if(input[i] >= 'A' && input[i] <= 'Z')
{
if((input[i]-'A'-key) < 0)/*如果此項小於0.則說明該字元在加密時是從後往前移 
key=3
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z*/
output[i] = (input[i]-'A'-key) % Q + 'Z' + 1;// 
else
output[i] = input[i]-key;// 
}
else if(input[i] >= 'a' && input[i] <= 'z')
{
if((input[i]-'a'-key) < 0)
output[i] = (input[i]-'a'-key) % Q + 'z' + 1;
else
output[i] = input[i]-key;
}
else
output[i] = input[i];

}

}



不上圖了,自己看