WHY2/src/decrypter.c

92 lines
2.0 KiB
C
Raw Normal View History

2022-05-01 16:23:07 +02:00
#include <why2/decrypter.h>
2022-03-20 18:12:25 +01:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
2022-05-01 16:23:07 +02:00
#include <why2/flags.h>
#include <why2/misc.h>
2022-03-20 18:12:25 +01:00
char*
decryptText(char *text, char *key)
{
//CHECK FOR INVALID key
2022-04-09 17:53:51 +02:00
if (strlen(key) < KEY_LENGTH)
2022-03-20 18:12:25 +01:00
{
2022-04-23 18:47:03 +02:00
fprintf(stderr, "Key must be at least %d characters long!\n", KEY_LENGTH);
2022-03-20 18:12:25 +01:00
exit(INVALID_KEY);
}
2022-04-26 19:04:43 +02:00
//REDEFINE KEY_LENGTH
#undef KEY_LENGTH
#define KEY_LENGTH strlen(key)
2022-03-20 18:12:25 +01:00
//VARIABLES
char *returningText;
2022-04-27 18:16:37 +02:00
int numberBuffer = 1;
2022-03-20 18:12:25 +01:00
char *textBuffer;
2022-04-27 18:16:37 +02:00
int textKeyChainLength;
2022-04-27 18:17:35 +02:00
int *textKeyChain;
2022-03-20 18:12:25 +01:00
2022-03-20 18:49:26 +01:00
//GET LENGTH OF returningText AND textKeyChain
2022-03-20 18:12:25 +01:00
for (int i = 0; i < strlen(text); i++)
{
if (text[i] == ENCRYPTION_SEPARATOR) numberBuffer++;
}
2022-04-27 18:16:37 +02:00
//SET LENGTH (numberBuffer)
2022-03-20 18:12:25 +01:00
returningText = malloc(numberBuffer);
2022-04-27 18:17:35 +02:00
textKeyChain = malloc(numberBuffer * sizeof(int));
2022-03-20 18:12:25 +01:00
int encryptedTextKeyChain[numberBuffer];
2022-04-27 18:16:37 +02:00
textKeyChainLength = numberBuffer;
2022-03-20 18:12:25 +01:00
//LOAD textKeyChain
2022-04-27 18:16:37 +02:00
generateTextKeyChain(key, textKeyChain, numberBuffer);
2022-03-20 18:12:25 +01:00
//LOAD encryptedTextKeyChain
for (int i = 0; i < (sizeof(encryptedTextKeyChain) / sizeof(int)); i++)
{
numberBuffer = 0;
//GET LENGTH OF EACH CHARACTER
for (int j = 0; j < strlen(text); j++)
{
if (text[j] == ENCRYPTION_SEPARATOR) break;
numberBuffer++;
}
textBuffer = malloc(numberBuffer);
//LOAD textBuffer
for (int j = 0; j < strlen(text); j++)
{
textBuffer[j] = text[j];
if (numberBuffer == j) break;
}
encryptedTextKeyChain[i] = atoi(textBuffer);
text += numberBuffer + 1;
free(textBuffer);
}
//DECRYPT TEXT
2022-04-27 18:16:37 +02:00
for (int i = 0; i < textKeyChainLength; i++)
2022-03-20 18:12:25 +01:00
{
textKeyChain[i] -= encryptedTextKeyChain[i];
}
//LOAD returningText
2022-04-27 18:16:37 +02:00
for (int i = 0; i < textKeyChainLength; i++)
2022-03-20 18:12:25 +01:00
{
returningText[i] = (char) textKeyChain[i];
}
2022-04-27 18:18:40 +02:00
//DEALLOCATION
free(textKeyChain);
2022-03-20 18:12:25 +01:00
return returningText;
}