96 lines
2.1 KiB
C
Executable File
96 lines
2.1 KiB
C
Executable File
#include "cesar.h"
|
|
|
|
/*
|
|
s -> path source
|
|
d -> path destination
|
|
key -> key of encryption
|
|
This function encrypt data
|
|
*/
|
|
int cryptCesar(const char *s, const int key, const int countCharact, char *bufferDst) {
|
|
char *buffer;
|
|
int i;
|
|
int error = countCharact;
|
|
|
|
if(error == -1) return error;
|
|
|
|
/* Allocation dynamique */
|
|
buffer = malloc(countCharact + 1); /* + 1 for '\0' */
|
|
|
|
/* Copy the data of file in the buffer[] */
|
|
error = copyFile(s, buffer);
|
|
if(error != 0) return error;
|
|
|
|
/********* Encryption **********/
|
|
for(i = 0; i < countCharact; i++) {
|
|
int val = 0;
|
|
/* For characters of A to Z */
|
|
if(buffer[i] >= 'A' && buffer[i] <= 'Z') {
|
|
if(buffer[i] + key > 'Z')
|
|
val = ((buffer[i] - 'A')-26) + key + 'A';
|
|
else
|
|
val = (buffer[i] - 'A') + key + 'A';
|
|
}
|
|
/* For characters of 'a' to 'z' */
|
|
else if(buffer[i] >= 'a' && buffer[i] <= 'z') {
|
|
if(buffer[i] + key > 'z')
|
|
val = ((buffer[i] - 'a')- 26) + key + 'A';
|
|
else
|
|
val = (buffer[i] - 'a') + key + 'A';
|
|
}
|
|
/* For others characters */
|
|
else val = buffer[i];
|
|
|
|
bufferDst[i] = val;
|
|
}
|
|
|
|
bufferDst[i] = '\0';
|
|
|
|
/* Freedom the memory */
|
|
free(buffer);
|
|
|
|
return error;
|
|
}
|
|
/*
|
|
s -> path source
|
|
d -> path destination
|
|
key -> key of decryption
|
|
This function decryption by Cesar
|
|
*/
|
|
int decryptCesar(const char *s, const int key, const int countCharact, char *bufferDst) {
|
|
int error = countCharact;
|
|
char *buffer;
|
|
int i;
|
|
|
|
if(error == -1)
|
|
return error;
|
|
|
|
/* Allocation dynamique */
|
|
buffer = malloc(countCharact + 1); /* +1 for '\0' */
|
|
|
|
/* Copy the data from file to buffer */
|
|
error = copyFile(s, buffer);
|
|
if(error != 0) return error;
|
|
|
|
/********* Decryption **********/
|
|
for(i = 0; i < countCharact; i++) {
|
|
int val = 0;
|
|
/* buffer[i] >= 'A' AND buffer[i] <= 'Z' */
|
|
if(buffer[i] >= 65 && buffer[i] <= 90) {
|
|
val = buffer[i] - key;
|
|
/* val < 'A' */
|
|
if(val < 65)
|
|
val = val + 26;
|
|
}
|
|
else
|
|
val = buffer[i];
|
|
|
|
bufferDst[i] = val;
|
|
}
|
|
bufferDst[i] = '\0';
|
|
|
|
/* Freedom the memory */
|
|
free(buffer);
|
|
|
|
return error;
|
|
}
|