1

I am writing a decryption class (AES/CBC/PKCS7Padding) where the encrypted data is coming from C#. I want to take the following string (which is base64 encoded):

usiTyri3/gPJJ0F6Kj9qYL0w/zXiUAEcslUH6/zVIjs=

and convert it to a byte array in java to pass into the SecretKeySpec as the key. I know there is the issue of C# having unsigned bytes and java only having signed bytes. How then can I pass this sting which has values greater than 127 within it and have java accept the key and initialization vectors?

  • 2
    Duplicate of http://stackoverflow.com/questions/469695/decode-base64-data-in-java (which has a good answer). – Michael Myers May 14 '09 at 20:17
  • Although the accepted answer isn't very good ... use the one with the highest points instead – kdgregory May 14 '09 at 20:20
  • Maybe I'm reading too much into the question, but I'm guessing the accepted answer is probably best for this application. No need to introduce more complexity into a solution that isn't likely to benefit from it. – erickson May 14 '09 at 20:23
  • If you pass a base64 encoded string into that class provided by sun, and the string is encoded from C# or a language that supports unsigned bytes, then you will get negative values in java. that sun class is also not documented. –  May 14 '09 at 20:25
  • 1
    Signed vs. unsigned should not be an issue here. – jdigital May 14 '09 at 20:33
  • Ken, the Java libraries work with the negative values in the byte array; that is, they "understand" that the signed byte value simply represents 8 bits, and don't treat the high bit as a sign. – erickson May 14 '09 at 21:12

1 Answers1

4

You don't have to worry about byte signedness because base64 encoded data never uses more than 6 bits in each byte (that's why it's called base 64, because you only use 64 characters which is 6 bits, to represent part of a data byte).

If your concern is the resulting data (3 data bytes for every 4 base64 characters), don't worry about that, either. An unsigned byte 255 in C# is the same as the signed byte -1 in Java.

To encode data, you can bitwise-and each byte with 0xff and store it in an int, then encode the least significant 8 bits. Or just bitwise-or each byte with 0x80 and store it in ant int and decode the least significant 8 bits.

But I think you would be better off using Bouncy Castle or the standard JCE to deal with all that stuff. The 'S' in PKCS7 means Standard so data encrypted in C# should decrypt fine in Java and vice versa.

Chochos
  • 5,155
  • 22
  • 27