Skip to content

Instantly share code, notes, and snippets.

@BobBurns BobBurns/aff_c.c
Created Jan 3, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.