52 lines
1.5 KiB
C
52 lines
1.5 KiB
C
#include <stdio.h>
|
|
|
|
// Code for encrypting
|
|
void encryptDecrypt(int mode) {
|
|
char input[100] = {0}; //Maximum length of the string is 100 characters
|
|
short pass; //Password should be within range 0~25
|
|
if (mode == 0) {
|
|
printf("Enter the string to be encrypted (no longer than 100 characters):\n");
|
|
}
|
|
else {
|
|
printf("Enter the string to be decrypted (no longer than 100 characters):\n");
|
|
}
|
|
scanf("%s",input);
|
|
printf("Enter your password (0-25): ");
|
|
scanf("%hd", &pass);
|
|
// Go through every character in input
|
|
for (int i = 0; i < 100; i++){
|
|
if (input[i] == '\0') {
|
|
// '\0' means we have reached the string's end.
|
|
break;
|
|
}
|
|
else {
|
|
input[i] -= 'A'; //Calculate the chacter's place in the alphabet, from 0~25
|
|
if (mode == 0) {
|
|
input[i] += pass; //Add the offset of pass
|
|
}
|
|
else {
|
|
input[i] -= pass; //Subtract the offset of pass
|
|
input[i] += 26; //Avoid negative number
|
|
}
|
|
input[i] %= 26; //Prevent the number from overflow
|
|
input[i] += 'A'; //Turn the number into ASCII again.
|
|
printf("%c", input[i]);
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
char mode;
|
|
printf("Slect Mode: (1) Encypt (2) Decrypt: ");
|
|
mode = getchar();
|
|
if (mode == '1') {
|
|
encryptDecrypt(0);
|
|
}
|
|
else if (mode == '2') {
|
|
encryptDecrypt(1);
|
|
}
|
|
else {
|
|
printf("Unrecognized command.");
|
|
}
|
|
return 0;
|
|
} |