terl / lazysodium-java

A Java implementation of the Libsodium crypto library. For the lazy dev.
https://github.com/terl/lazysodium-java/wiki
Mozilla Public License 2.0
134 stars 46 forks source link

Padding returns unexpected results #85

Closed ionspin closed 3 years ago

ionspin commented 3 years ago

sodium_pad in libsodium is specified as:

int
sodium_pad(size_t *padded_buflen_p, unsigned char *buf,
           size_t unpadded_buflen, size_t blocksize, size_t max_buflen)

While in lazysodium it's

public native int sodium_pad(Pointer paddedBuffLen, char[] buf, int unpaddedBufLen, int blockSize, int maxBufLen);

The problem is caused by mismatch of char size in java and C, in C it's one byte, but in Java it's 2.

Modifying padding tests a bit demonstrates the problem

 @Test
    public void pad() {
        IntByReference ref = new IntByReference(0);
        char[] b = {'a','b','c','d'};

        lazySodium.sodiumPad(ref, b, 4, 4, 10);
        TestCase.assertEquals(8, ref.getValue());
    }

Results in

b
 0 = 'a' 97
 1 = 'b' 98
 2 = '\u0080' 128
 3 = '\u0000' 0
gurpreet- commented 3 years ago

I've updated PaddingTest.java with new code showing how to correctly create a pointer to some memory which is then padded.