c - some problem with byte xor [closed]
I have to make some binary xor on 2 byte buffers. one is an encoding key, the other the encoded value.
at the moment my code looks like this:
BYTE key[]={"somekey"}
BYTE value[]={"somevalue"};
for(i= 0; i < vallLength; i++)
{
valBuf[i] = value[i] ^ key[i % keyLen开发者_Python百科gth];
}
this does not work for me. what am i doing wrong?
Alright, this is terrible, but I felt like writing some easy code for a change.
#include <stdio.h>
char key[] = "This is a fancy key.";
char text[] = "Encrypt this extremely long plaintext.";
#define KEY_LEN (sizeof(key))
#define TXT_LEN (sizeof(text))
void crypt(char *key, char *plaintext, char *ciphertext, int keyLen, int ptLen)
{
int idx;
for (idx = 0; idx < ptLen; idx++)
{
ciphertext[idx] = plaintext[idx] ^ key[idx % keyLen];
}
}
int main()
{
printf("Plaintext before:\n\t%s\n", text);
crypt(key, text, text, KEY_LEN, TXT_LEN);
printf("Plaintext after:\n\t%s\n", text);
crypt(key, text, text, KEY_LEN, TXT_LEN);
printf("Plaintext after after:\n\t%s\n", text);
return 0;
}
This question's destined for closure anyway, so it can't hurt too much to post it here.
Are the arrays "key" and "value" the same length? I'm not sure of the result you are looking for, but you might want to ONLY loop over the shorter length, then pad the longer array values to the ^ answer.
BYTE* xx = new BYTE[SIZEX];
BYTE* yy = new BYTE[SIZEY];
int nCount = Min(xx.Length(), yy.Length());
BYTE* answer = new BYTE[Max(xx.Length(), yy.Length())];
for(int ii=0; ii<nCount; ++ii)
answer[ii] = xx[ii] ^ y[ii];
BYTE* zz;
if(xx.Length() > yy.Length())
zz = xx;
else
zz = yy;
for(int ii=nCount; ii<Max(xx.Length(), yy.Length()); ++ii)
answer[ii] = zz[ii];
It could be because "i % keyLength" is undefined for the first run of your loop as i=0
精彩评论