tags:

views:

95

answers:

1

After looking into a bug in the original jBCrypt v0.1 C# port: BCrypt.net (Related Question). I decided to compare the new jBCrypt code against the old C# port to look for discrepancies and potential issues like the related question's bug.

Here is what I've found:

// original java (jBCrypt v0.3):
private static int streamtoword(byte data[], int offp[]) {
        int i;
        int word = 0;
        int off = offp[0];

        for (i = 0; i < 4; i++) {
            word = (word << 8) | (data[off] & 0xff);
            off = (off + 1) % data.length;
        }

        offp[0] = off;
        return word;
}


// port to C# :
private static uint StreamToWord(byte[] data, ref int offset)
{

    uint word = 0;

    for (int i = 0; i < 4; i++)
    {
        // note the difference with the omission of "& 0xff"
        word = (word << 8) | data[offset];
        offset = (offset + 1) % data.Length;
    }

    return word;
}

if the prior is incorrect would the following fix it?

private static uint StreamToWord(byte[] data, ref int[] offsetp)
{

    uint word = 0;
    int offset = offsetp[0];
    for (int i = 0; i < 4; i++)
    {
        word = (word << 8) | (uint)(data[offset] & 0xff);
        offset = (offset + 1) % data.Length;
    }

    offsetp[0] = offset;

    return word;
}
+4  A: 

The & 0xff is required in the Java version because in Java, bytes are signed. (Some argue that this is a bug.)

In C#, bytes are unsigned, so the & 0xff is unnecessary.

Chris Jester-Young
Thanks. :o) You wouldn't happen to know what was updated to fix this security issue (http://www.mindrot.org/files/jBCrypt/internat.adv), would you? I'd like to up the C# ported version.
David Murdoch
Yes, it was fixed to use UTF-8 instead of US-ASCII to convert the chars in the passphrase to bytes. In Java, if a character can't be encoded, it is replaced with ?, rather than throwing an exception.
Chris Jester-Young
@David: Thankfully it seems BCrypt.NET already does the Right Thing in that department, so you have no worries. :-D
Chris Jester-Young
muchos gracias, sir. I can now sleep soundly. :o)
David Murdoch