WHY2/src/lib/decrypter.c

97 lines
2.2 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
2022-05-06 17:43:00 +02:00
outputFlags decryptText(char *text, char *key, inputFlags flags)
2022-03-20 18:12:25 +01:00
{
//CHECK FOR INVALID key
2022-05-03 18:37:28 +02:00
if (strlen(key) < getKeyLength())
2022-03-20 18:12:25 +01:00
{
2022-05-08 19:41:20 +02:00
if (!flags.noOutput) fprintf(stderr, "Key must be at least %d characters long!\n", getKeyLength());
2022-03-20 18:12:25 +01:00
exit(INVALID_KEY);
}
2022-04-26 19:04:43 +02:00
2022-05-03 18:37:28 +02:00
//REDEFINE keyLength
setKeyLength(strlen(key));
2022-04-26 19:04:43 +02:00
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)
returningText = malloc(numberBuffer);
textKeyChain = malloc(sizeof(int) * numberBuffer);
int encryptedTextKeyChain[sizeof(int) * 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++)
2022-03-20 18:12:25 +01:00
{
numberBuffer = 0;
//GET LENGTH OF EACH CHARACTER
for (int j = 0; j < strlen(text); j++)
{
if (text[j] == ENCRYPTION_SEPARATOR) break;
numberBuffer++;
}
textBuffer = malloc(sizeof(char) * numberBuffer);
2022-03-20 18:12:25 +01:00
//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-05-06 17:43:00 +02:00
//LOAD output
outputFlags output =
{
returningText, //DECRYPTED TEXT
key //USED KEY
};
//DEALLOCATION
free(textKeyChain);
2022-05-06 17:43:00 +02:00
return output;
2022-03-20 18:12:25 +01:00
}