93 lines
1.9 KiB
C
Executable File
93 lines
1.9 KiB
C
Executable File
#include "caesar.h"
|
|
|
|
/*
|
|
s -> path source
|
|
d -> path destination
|
|
key -> key of encryption
|
|
This function encrypt data
|
|
*/
|
|
int cryptCaesar(const char *s, const int key, const int countCharact, char *bufferDst) {
|
|
char *buffer;
|
|
int i;
|
|
int error = countCharact;
|
|
char c = 0;
|
|
|
|
if(error == -1) return error;
|
|
|
|
/* Allocation dynamique */
|
|
buffer = malloc(countCharact + 1); /* + 1 for '\0' */
|
|
|
|
/* Copy the data of file into 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') {
|
|
c = buffer[i] - 'A';
|
|
val = ((c + key) % 26) + 'A';
|
|
}
|
|
/* For characters of 'a' to 'z' */
|
|
else if(buffer[i] >= 'a' && buffer[i] <= 'z') {
|
|
c = buffer[i] - 'a';
|
|
val = ((c + key) % 26) + '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 decryptCaesar(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 into 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;
|
|
}
|