cryptography/src/polybius.c
2024-09-25 12:03:08 +02:00

67 lines
1.8 KiB
C

#include "polybius.h"
void cryptPolybius(const char *filename, const char *key){
char polybius[POLYBIUS_SIZE][POLYBIUS_SIZE];
generateSquarePolybius(polybius, key);
for (int i = 0; i < POLYBIUS_SIZE; i++){
for (int j = 0; j < POLYBIUS_SIZE; j++)
printf("%c ", polybius[i][j]);
printf("\n");
}
}
/*
This function fill the polybius square
*/
static void fillSquare(int pos, int *posPolybius, char *p, char polybius[POLYBIUS_SIZE][POLYBIUS_SIZE]){
for (int i = 0; i < 5; i++){
polybius[pos][i] = p[*(posPolybius)];
*posPolybius = *posPolybius + 1;
}
}
static int findKeyInSquare(const char *polybius, char c){
// We exclude the 'J' character
for (int i = 0; i < ALPHABET_SIZE - 1; i++)
if (c == polybius[i])
return 1;
return 0;
}
/*
This function generate the polybius square
*/
void generateSquarePolybius(char polybius[POLYBIUS_SIZE][POLYBIUS_SIZE], const char *key){
char a[ALPHABET_SIZE - 1] = {0}; // The size is 25, we exclude the J character
int pos = 0;
for (int i = 0; i < strlen(key); i++){
char k;
if (key[i] >= 'a' && key[i] <= 'z')
k = key[i] - 32; // 32 = 26 + special characters
else k = key[i];
int res = findKeyInSquare(a, k);
if (res == 0)
a[pos++] = k;
}
int n = 0;
int t = pos;
for (int i = pos; i < ALPHABET_SIZE + pos; i++){
char c = 'A' + n;
if (c != 'J'){
int res = findKeyInSquare(a, c);
if (res == 0)
a[t++] = c;
}
n++;
}
pos = 0;
fillSquare(0, &pos, a, polybius);
fillSquare(1, &pos, a, polybius);
fillSquare(2, &pos, a, polybius);
fillSquare(3, &pos, a, polybius);
fillSquare(4, &pos, a, polybius);
}