I was just looking for a general feedback about this code, which encrypts a file with the Tiny Encryption Algorithm. I'm currently studying C, and I wanted to know if there was anything I could improve in my coding style or anything. Sorry for my english.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BASE_DELTA 0x9e3779b9
#define KEY_VALUE 0x7A24432646294A404E635266556A586E //128bits value
void encrypt (u_int32_t* v, u_int32_t* k) {
u_int32_t delta = BASE_DELTA * 1;
for (int i = 1; i <= 32; i++) {
v[0] += (v[1] * delta) ^ ((v[1] << 4) + k[0]) ^ ((v[1] >> 5) + k[1]);
v[1] += (v[0] * delta) ^ ((v[0] << 4) + k[2]) ^ ((v[0] >> 5) + k[3]);
delta += BASE_DELTA;
}
}
void encryptFile(const char file_to_encrypt_path[], u_int32_t key[4]){
u_int32_t block[2];
int nb_bytes_read = 0;
int fd_to_encrypt = open(file_to_encrypt_path, O_RDONLY, 0655); //RDONLY permissions are 0655
int fd_result_file = open("encrypted_file.dec", O_CREAT|O_TRUNC|O_WRONLY, 0666);
while(1){
memset(block, 0x0, sizeof(u_int64_t));
nb_bytes_read = read(fd_to_encrypt, block, sizeof(u_int64_t));
if(nb_bytes_read == -1){
perror("read");
exit(errno);
}
if(nb_bytes_read == 0){
break; //EOF
}
encrypt(block, key);
if(write(fd_result_file, block, sizeof(u_int64_t)) ==-1){
perror("write");
exit(errno);
}
}
}
int main(int argc, char const *argv[]) {
if (argc < 2){
printf("usage : %s <file to encrypt> \n", argv[0]);
exit(EXIT_FAILURE);
}
u_int32_t key[4];
u_int32_t block[2];
memset(key, 0x0, sizeof(u_int32_t) * 4);
memset(block, 0x0, sizeof(u_int32_t) * 2);
__uint128_t key_val = KEY_VALUE; //Note that __uint128_t requiers gcc version > 4.4
*key = key_val;
encryptFile(argv[1], key);
return 0;
}
u_int32_t
,u_int64_t
, and so on. (Or just use the standarduint32_t
etc. located in<stdint.h>
.) \$\endgroup\$unistd.h
, according to my compiler.u_int32_t
equalsuint32_t
, etc. \$\endgroup\$