简体   繁体   中英

Difference between this Java and C code?

I tried to convert some C code to Java, but it is working slightly different. It is XOR encryption and for some data it returns the same results, so I know it is pretty close, but for some data it doesn't work exactly the same (different results).

C code (runs on x86 Windows, compiled with Borland Builder):

void Crypt(unsigned char *data,long len)
{
char key[] = "X02$B:";
ULONG crypt_ptr;
long x;

   for(crypt_ptr=0,x=0;x<len;x++)
      {
      data[x] ^= key[crypt_ptr];
      if(crypt_ptr < (sizeof(key) - 2))
         key[crypt_ptr] += key[crypt_ptr + 1];
      else
         key[crypt_ptr] += key[0];
      if(!key[crypt_ptr])
         key[crypt_ptr] += (char) 1;
      if(++crypt_ptr >= sizeof(key) - 1)
         crypt_ptr = 0;
      }
}

Java Code (which runs on the Android platform if it matters):

public static void Crypt(byte[] data,int offset,int len) 
{ 
    // EDIT: Changing this to byte[] instead of char[] seems to have fixed code
    //char[] key = {'X','0','2','$','B',':'};
    byte[] key = {'X','0','2','$','B',':'};
    int size_of_key = 7;
    int crypt_ptr; 
    int x; 

    for(crypt_ptr=0,x=0;x<len;x++) 
    { 
        data[x+offset] ^= key[crypt_ptr]; 
        if(crypt_ptr < (size_of_key - 2)) 
            key[crypt_ptr] += key[crypt_ptr + 1]; 
        else 
            key[crypt_ptr] += key[0]; 
        if(key[crypt_ptr] == 0) 
            key[crypt_ptr] += (char) 1; 
        if(++crypt_ptr >= size_of_key - 1) 
            crypt_ptr = 0; 
    } 
}

I have confirmed that the data going in to each function is the same, and for the Java version I am passing in the correct offset value within the byte array. As mentioned, it works sometimes, so I don't think it is a major/obvious issue, more like some minor issue between signed vs unsigned values. If it helps at all, the first byte that was different was at byte 125 (index 124 if zero-based) in the data. I didn't see a pattern though, like every 125 bytes, it was pretty much random after that. The data is only 171 bytes, and I can figure out how to post as an attachment probably if needed, but I don't think it is.

I guess it's because char is 16-bit in java. So when you increment key key[crypt_ptr] += (char) 1 or add two chars key[crypt_ptr] += key[crypt_ptr + 1] , it acts in different way from c (where char is 8-bit).

Try to use bytes everywhere instead of chars, just use symbol codes for initialization.

Why don't you show us an example where the differences manifest themselves?

BTW, I would write:

char[] key = {'X','0','2','$','B',':', '\0'};

Your key values need to be 8-bit. Try

byte[] key = "X02$B:".getBytes();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM