1

I have a problem with AES encryption and the customer showed me their PHP server code for "decrypting". Curiously enough the exact code has been taken from S.O. (not surprising). I found this out because the code the customer passed me had the exact same comment! :)

Anyway, it's a piece of PHP code taken from this S.O. question.

I am trying to do the same with Java but I don't know what this exact line is adding:

$key = 'a16byteslongkey!';

$padded_key = $key . str_repeat(chr(0x00), 16); // Argh!

(note the // Argh! comment was not mine ;)

Is it trying to add chr(0x00) to make a 32 bytes key (because the $key is 16?) if so, how would I do the same in Java?

Community
  • 1
  • 1
Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144
  • @Josh perhaps I should have clarified: what is chr(0x00) doing in php? – Martin Marconcini Mar 21 '12 at 17:32
  • In PHP, strings are binary-safe (every "character" in the string is in fact just a byte), but Java's `String` instances are not (they actually represent characters, not bytes). For binary encryption keys you probably shouldn't be using `String` objects but rather a `byte[]` or something like a `Key` class. – Another Code Mar 21 '12 at 17:54
  • @AnotherCode Indeed, thanks for the clarification. Turns out the customer was doing a "hacky" thing on the server side, completing the 16 bytes key with 16 zeros so it adds 32… after padding the fixed key with 16 "zeros" it all worked. ;) – Martin Marconcini Mar 21 '12 at 18:00

2 Answers2

2

As Gareth stated this returns the character with ASCII code 0. Using this we can make a function which repeats a string:

public static String strRepeat(String toRepeat, int reps){
    //Sanity checks go here!
    StringBuilder sb = new StringBuilder();
    for(int x = 0; x < reps; x++){
        sb.append(toRepeat);
    }
    return sb.toString();
}

Now the line can be replaced with:

String paddedKey = key + strRepeat('\0', 16); // Argh!
Jim
  • 22,354
  • 6
  • 52
  • 80
1

chr(0x00) should return the character with the ASCII code 0 which I think can be represented by '\0' in Java.

Gareth
  • 5,693
  • 3
  • 28
  • 37