hms2010

Caesar.c

Nov 8th, 2016
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. void encrypt(char* text, size_t text_len, char key){
  6.     int i = 0;
  7.  
  8.     for (i = 0; i < text_len; i++){
  9.             if (('a' <= text[i]) && (text[i] <= 'z')){
  10.                 text[i] = 'a' + (1 + (text[i] + key) % 'a') % 26;
  11.             }
  12.             else if(('A' <= text[i]) && (text[i] <= 'Z')){
  13.                 text[i] = 'A' + (1 + (text[i] + key + 'A' - 'a') % 'A') % 26;
  14.             }
  15.     }
  16. }
  17.  
  18. void decrypt1(char* text, size_t text_len, char key){
  19.     int i = 0;
  20.     key = 'z' - key + 'a' + 1;
  21.  
  22.     for (i = 0; i < text_len; i++){
  23.             if (('a' <= text[i]) && (text[i] <= 'z')){
  24.                 text[i] = 'a' + (text[i] + key - 1) % 'a' % 26;
  25.             }
  26.             else if(('A' <= text[i]) && (text[i] <= 'Z')){
  27.                 text[i] = 'A' + (text[i] + key + 'A' - 'a' - 1) % 'A' % 26;
  28.             }
  29.     }
  30. }
  31.  
  32. void decrypt2(char* text, size_t text_len, char key){
  33.     int i = 0;
  34.  
  35.     for (i = 0; i < text_len; i++){
  36.             if (('a' <= text[i]) && (text[i] <= 'z')){
  37.                 text[i] = 'a' + ('z' + text[i] - key) % 'a' % 26;
  38.             }
  39.             else if(('A' <= text[i]) && (text[i] <= 'Z')){
  40.                 text[i] = 'A' + ('Z' + text[i] - key - 'A' + 'a') % 'A' % 26;
  41.             }
  42.     }
  43. }
  44.  
  45. int main(){
  46.     char text[256];
  47.     size_t text_len;
  48.     char k = 'c';
  49.  
  50.     scanf("%s", &text);
  51.     text_len = strlen(text);
  52.     encrypt(text, text_len, k);
  53.     printf("Plain  text: %s\n", text);
  54.  
  55.     decrypt1(text, text_len, 'c');
  56.     printf("decrypt1\nCipher text: %s\n", text);
  57.  
  58.     encrypt(text, text_len, k);
  59.  
  60.     decrypt2(text, text_len, k);
  61.     printf("decrypt2\nCipher text: %s\n", text);
  62.  
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment