Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int encrypt(int num);
- int decrypt(int encryptedNum);
- int encryptMenu(void);
- int decryptMenu(void);
- int main(void)
- {
- char choice = '0';
- START:
- printf("%s\n\n%s\n%s\n\n%s", "Do you want to encrypt or decrypt a code?",
- "[E\\e] - To Encrypt",
- "[D\\d] - To Decrypt",
- "Your answer: ");
- scanf("%c", &choice);
- switch (choice)
- {
- case 'e':
- case 'E':
- encryptMenu(); // prints encryption menu
- break;
- case 'd':
- case 'D':
- decryptMenu(); // prints decryption menu
- break;
- default:
- puts("Type in either 'e' or 'd'.");
- goto START;
- break;
- }
- }
- int encrypt(int num)
- {
- int d1, d2, d3, d4; // 4 digits of the number to be separated
- int result; // encrypted integer to be returned
- // Separate digits
- d4 = num % 10;
- num /= 10;
- d3 = num % 10;
- num /= 10;
- d2 = num % 10;
- num /= 10;
- d1 = num;
- // Add 7 to each
- d1 += 7;
- d2 += 7;
- d3 += 7;
- d4 += 7;
- // Get the remainder when divided by 10
- d1 %= 10;
- d2 %= 10;
- d3 %= 10;
- d4 %= 10;
- // Swap digit 1 with 3, and 2 with 4
- result = d3 * 1000 + d4 * 100 + d1 * 10 + d2;
- return result;
- }
- int decrypt(int encryptedNum)
- {
- int d1, d2, d3, d4; // 4 digits of the number to be separated
- int result; // encrypted integer to be returned
- // Separate digits
- d4 = encryptedNum % 10;
- encryptedNum /= 10;
- d3 = encryptedNum % 10;
- encryptedNum /= 10;
- d2 = encryptedNum % 10;
- encryptedNum /= 10;
- d1 = encryptedNum;
- // Add 10, if the number was previously divided
- if (d1 < 8 && d1 > 0)
- d1 += 10;
- if (d2 < 8 && d2 > 0)
- d2 += 10;
- if (d3 < 8 && d3 > 0)
- d3 += 10;
- if (d4 < 8 && d4 > 0)
- d4 += 10;
- // Substract 7 from each
- d1 -= 7;
- d2 -= 7;
- d3 -= 7;
- d4 -= 7;
- // Swap digit 1 back with 3, and 2 with 4
- result = d3 * 1000 + d4 * 100 + d1 * 10 + d2;
- return result;
- }
- int encryptMenu(void)
- {
- int input;
- printf("\n%s", "Enter a 4-digit integer: ");
- scanf("%d", &input);
- if (input < 1000 || input > 9999) // make sure input is a 4-digit integer
- {
- puts("4-digit integer is required!");
- encryptMenu(); // go back and ask for an input again
- }
- printf("\nYour encrypted integer is: %d\n\n", encrypt(input));
- main();
- }
- int decryptMenu(void)
- {
- int input;
- printf("\n%s", "Enter an encrypted 4-digit integer: ");
- scanf("%d", &input);
- if (input < 1000 || input > 9999) // make sure input is a 4-digit integer
- {
- puts("4-digit integer is required!");
- decryptMenu(); // go back and ask for an input again
- }
- printf("\nYour encrypted integer is: %d\n\n", decrypt(input));
- main();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement