arrays - Memory error - Simple XOR encryption in C -
i having memory issues printing hex in following format: \xaa\xab\xdc using encryption routine.
i did modifications, using snprintf()
, strcat()
in attempt fix output , worked degree.
this function started out with, better modified version.
char *encrypt(char key, const char *a) { char *output = malloc(strlen(a)+1); bzero(output, strlen(a)+1); strcpy(output, a); char *tmp = output; int i; (i = 0; tmp[i] != 0; i++) { tmp[i] = key ^ tmp[i]; } return output; }
my current progress follows:
char *encrypt(char key, const char *a) { char buf[256]; char *tmp = a; int i; int *k; (i = 0; tmp[i] != 0; i++) { char temp[10]; k = key ^ tmp[i]; snprintf(temp, sizeof(temp), "\\x%s", k); strcat(buf, temp); } return buf; } int main(int argc, char **argv) { if (argv[1] == null){ printf("usage: %s <string>\n", argv[0]); } else printf("encrypted string: %s\n", encrypt(0xeb, argv[1])); return 0; }
if point me in right direction on how fix memory issue, , if code can improved appreciate lot.
instead of:
int *k; k = key ^ tmp[i]; snprintf(temp, sizeof(temp), "\\x%s", k);
use this:
unsigned char k; k = key ^ tmp[i]; snprintf(temp, sizeof temp, "\\x%02x", k);
note have other changes make regarding buf
. firstly never initialize it, appending junk. , never check didn't overflow it.
also attempt return function, however, since local variable, ceases exist when function returns.
see this thread suggestions of how freshly-written string out of function. use malloc(256)
in same vein first attempt (and remember replace sizeof buf
mallocated length, in snprintf
call).
it'd more robust use unsigned char
instead of char
both key , message. example of issues on x86 or x64, char
has range of -128
127
when supply 0xeb
(i.e. 235
) out-of-range assignment not well-defined.
but on common systems away using char
because tend define out-of-range assignment using 2's complement , truncating excess bits, works in situation.
Comments
Post a Comment