Question

I have an application in C# that encrypt part of my files (because they are big files) using RijndaelManaged. So I convert my file to byte arrays and encrypt only a part of it.

Then I want to decrypt the file using Java. So I have to decrypt only part of the file (means those bytes) that was encrypted in C#.

Here the problem comes. Because in C# we have unsigned bytes and in Java we have signed bytes. So my encryption and decryption not working the way I want.

In C# I have joined the encrypted bytes and normal bytes together and saved them with File.WriteAllBytes. So I can't use sbyte here or I don't know how to do it:

byte[] myEncryptedFile = new byte[myFile.Length];
for (long i = 0; i < encryptedBlockBytes.Length; i++)
{
   myEncryptedFile[i] = encryptedBlockBytes[i];
}
for (long i = encryptedBlockBytes.Length; i < myFile.Length; i++)
{
   myEncryptedFile[i] = myFileBytes[i];

}

File.WriteAllBytes(@"C:\enc_file.big", myEncryptedFile);

( And there is an exact same code for decryption in Java )

So my questions are:

  • Is there any WriteAllsBytes in C#?
  • Or can I use unsigned bytes in Java?
  • Or any other solutions to my problem?
Was it helpful?

Solution

Although you cannot use unsigned bytes in Java, you may simply ignore the issue.

AES - and all modern symmetric ciphers - operates on bytes, and the input and output have been defined to be bytes (or octets). Input and output have been standardized by NIST and test vectors are available.

If you look at the separate bit content of the bytes then {200,201,202} in C# and {(byte)200, (byte)201, (byte)202} in Java are identical. This is because Java uses two-complement representation of bytes.

Take the number 200 as integer: this will be 11010000 in binary, representing the number -56 in Java if used in a (signed) byte in two complements. Now symmetric ciphers will simply transform these bits to another (normally using a full block of bits).

Once you have retrieved the answer you will see that they are identical both in C# and Java when you look at the separate bits. C# will however interpret those as unsigned values and Java as signed values.

If you want to print out or use these values as signed numbers in Java then you have to convert them to positive signed integers. The way to do this is to use int p = b & 0xFF.

This does the following (I'll use the number 200 again):

  1. The (negative) byte value is expanded to a signed integer, remembering the sign bit:

    11010000 becomes 11111111 11111111 11111111 11010000

  2. This value is "masked" with 0xFF or 00000000 00000000 00000000 11111111 by performing the binary AND operator:

    11111111 11111111 11111111 11010000 & 00000000 00000000 00000000 11111111 = 00000000 00000000 00000000 11010000

This value is identical to the value 200 as a signed integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top