Advertisement
trideceth12

affine cipher

Apr 17th, 2014
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. /**
  2. Affine cipher (WTFPL 2014 Jake Sebastian-Jones)
  3. */
  4. #include<stdio.h>
  5. #include<stdlib.h>
  6.  
  7. char inverse_values[26] = {0, 1, 0, 9, 0, 21, 0, 15, 0, 3, 0, 19, 0,
  8.                            0, 0, 7, 0, 23, 0, 11, 0, 5, 0, 17, 0, 25};
  9.  
  10. char encrypt(char x, int a, int b) {
  11.     if( x < 'A' || (x > 'Z' && x < 'a') || x > 'z' ) return x;
  12.     int oset = x <= 'Z' ? 'A' : 'a';
  13.     return (a * (x - oset) + b) % 26 + oset;
  14. }
  15.  
  16. char decrypt(char x, int inv, int b) {
  17.     if( x < 'A' || (x > 'Z' && x < 'a') || x > 'z' ) return x;
  18.     int oset = (x <= 'Z' ? 'A' : 'a');
  19.     int chk = inv * ((x - oset) - b) % 26;
  20.     return (chk >= 0 ? chk : 26 + chk) + oset;
  21. }
  22.  
  23. int main(int argc, char **argv) {
  24.     char c, inv;
  25.     int a = atoi(argv[1]);
  26.     int b = atoi(argv[2]) % 26;
  27.  
  28.     if(a > 25 || (inv = inverse_values[a]) == 0) {
  29.         fprintf(stderr, "Error: 'a' value must be less than "
  30.                         "and coprime with 26\n");
  31.         return 64;
  32.     }
  33.  
  34.     while( (c = fgetc(stdin)) != EOF) {
  35.         #ifdef DECRYPT
  36.             fprintf(stdout, "%c", decrypt(c, inv, b));
  37.         #else
  38.             fprintf(stdout, "%c", encrypt(c, a, b));
  39.         #endif
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement