Search code examples
javashaprimitivelibsodium

How do I represent uint8 literals in Java


I am trying to re-implement some code that uses libsodium in Java. The original code declares an array of type uint8:

#define SECRET ((uint8_t[]){ 0xAA, 0xBB, 0xCC ... }) // not the real secret!

and feeds that to libsodium's crypto_hash_sha256_update

My challenge in implementing this in Java is that Java has no unsigned bytes, so I can't actually type 0xAA as a byte.

Things I've tried:

  • Declaring my array as short/int: I think this breaks because of 0 padding
  • Declaring the literals as 0b11110000... format, this doesn't give the right answers (I have some test data from the original implementation)
  • Declaring an array of char [] and concatenating the literals: final char[] salt = { 0xAABB, 0xCCDD, ...}`, doesn't give right answers either

EDIT this is my short attempt

    final short[] salt = { 0xAA, 0xBB, ...};


    final Hasher hasher = Hashing.sha256().newHasher();
    hasher.putLong(input);
    for (int i=0; i < salt.length; i++) {
        hasher.putShort(salt[i]);
    }
    return hasher.hash().asBytes();

Solution

  • Looks like my original code worked

    final short[] salt = { 0xAA, 0xBB, ...};
    
    
    final Hasher hasher = Hashing.sha256().newHasher();
    hasher.putLong(input);
    for (int i=0; i < salt.length; i++) {
        hasher.putShort(salt[i]);
    }
    return hasher.hash().asBytes();
    

    The problem was I forgot to left-pad my result before comparing