Skip to content

Instantly share code, notes, and snippets.

@BobBurns
Created January 3, 2016 01:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BobBurns/cbb27eee0187b643d4b4 to your computer and use it in GitHub Desktop.
Save BobBurns/cbb27eee0187b643d4b4 to your computer and use it in GitHub Desktop.
c algorithm to decipher affine cipher
#include <stdio.h>
#include <stdlib.h>
/* quick program to solve affine cipher with key a, b mod 26 */
/* usage: ./aff_c <key a> <key b> <optional e=encrypt>
* cipher-text from stdin or pipe
*/
int
main(int argc, char *argv[]) {
int a, b, i;
char input[256], n;
long result;
if (argc < 3) {
printf("usage!\n");
return 1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
scanf("%s",&input);
printf("%d %d\n", a, b);
i=0;
while(input[i]!=0) {
/* shift cypher with formula */
/* error check */
if (input[i] < 0x60 || input[i] > 0x7a) {
printf("value not in set (a-z)!\n");
return 1;
}
result = input[i] - 0x61; /*first convert to set */
// printf("debug: a, b, result: %d %d %li\n", a, b, result);
if (argc == 4 && argv[3][0] == 'e') {
result = ((result * a) + b) % 26;
} else {
int j;
long p1, p2 = 0;
p1 = result - b;
if (p1 < 0)
p1 = abs(p1) * 25; // 25 == -1 in mod 26
for (j = 0; j < 26;j++) {
if ((j * a) % 26 == 1) {
p2 = j; // p2 is mul inv of a
break;
}
}
if (p2 == 0) {
printf(" no gcd for %d, %d\n", a, b);
return 1;
}
result = (p1 * p2) % 26;
}
result += 0x61;
printf("%c",result);
i++;
}
printf("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment