#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void str_to_hex(char text[]) {
char hex_text[2*strlen(text)+1];
for (int i=0, j=0; i < strlen(text); i++, j+=2) {
sprintf(hex_text+j, "%02X", text[i]);
}
hex_text[strlen(hex_text)] = '\0';
strcpy(text, hex_text);
}
void hex_to_str(char hex_text[]) {
char text[strlen(hex_text)/2+1];
int j=0;
for (int i=0; i < strlen(hex_text); i+=2) {
char hex_chars[3];
hex_chars[0] = hex_text[i];
hex_chars[1] = hex_text[i+1];
hex_chars[2] = '\0';
int decimal_value;
sscanf(hex_chars, "%x", &decimal_value);
text[j++] = (char) decimal_value;
}
text[j] = '\0';
strcpy(hex_text, text);
}
void xor_encryptor(char text[], char key[]) {
char encrypted_text[strlen(text)];
char encrypted_hex_text[strlen(text)*2+1];
for (int i=0, j=0; i < strlen(text); i++, j+=2) {
encrypted_text[i] = text[i] ^ key[i % strlen(key)];
sprintf(encrypted_hex_text+j, "%02X", encrypted_text[i]);
}
encrypted_hex_text[strlen(text) * 2 - 1] = '\0';
strcpy(text, encrypted_hex_text);
}
void xor_decryptor(char text[], char key[]) {
int non_hex_str_len = strlen(text)/2;
char decrypted_text[non_hex_str_len+1];
hex_to_str(text);
for (int i=0; i < non_hex_str_len; i++) {
decrypted_text[i] = text[i] ^ key[i % strlen(key)];
}
strcpy(text, decrypted_text);
}
int main() {
char data[] = "Hello World";
xor_encryptor(data, "lol");
printf("%s\n", data);
xor_decryptor(data, "lol");
printf("%s", data);
return 0;
}
I am very bad at coding and C.ik this code is bad, I just wonna bring it to working. Encryptor is working fine ig.the decryptor is not printing the exact text.Suppose I encrypt Hello World with the encryptor function and dcrypt it, it prints Hel-\\ ⌠√. I tried alot before coming here