Search code examples
javaencodingcharacter-encodinghexsecure-random

JAVA Decode SHA1PRNG generated byte in hexa


I'm currently trying do implement a password hasher generator. But first, i'm trying to encode the randomly generated salt like this :

public static byte[] generateSalt()
        throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[8];
    random.nextBytes(salt);
    return salt;
}

How can i encode this in hexa, and then decode it to its original state ? I just want to show the hexa value of the generated salt to the user, so he can then decode it in the authenticate part. Of course this is for leaning purpose.

What i currently have

I tried this :

    try {
        byte[] new_salt;
        String salt_str;
        new_salt = PasswordHash.generateSalt();
        for(int i = 0; i < 8; i++) {
            salt_str += new_salt[i];
        }
        out_new_salt.setText(salt_str);
    }
    catch (Exception e) {
        System.out.print(e.getStackTrace() + "Something failed");
    }

The output looks like this : 67-55-352712114-12035 So ok, i can get the content of each byte. I tried to use Base 64 encoder, but it prints unknow character, i think it's because the content of the byte array has a 2exp8 range of values. I tried using :

System.out.println(new String(new_salt));

but it also prints unkown values. Using Charset.forName("ISO-8859-1") and Charset.forName("UTF-8") but it doesn't work. UTF-8 prints unknow characters and ISO-8859-1 weirdly works, but doesn't print as many numbers as the size of the byte array ( 8 ) I think hexa is what suits best what i want to do.


Solution

  • I finally find what i was looking for. This is a simple fonction I found here :

    How to convert a byte array to a hex string in Java? This works perfectly in my case.

    This is the function :

    private final static char[] hexArray = "0123456789ABCDEF".toCharArray();
    
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
    

    This looks like this : enter image description here