0

I try to convert byte array to string in java using new String( bytes, "UTF-8") method, but they only return the object. like this @AB4634bSbbfa

So, I searched some way to solve this problem.

I finally get valid string array, by converting hex-code to basic-character array. like this. char[] chars = {"0", "1", ... "e", "f"};

This never happened before why do i have to convert hex-code to get valid string.

Here is method. byte array which is hashed by Mac-sha-256 with specific key when i hashed.

    public static String getHashString() {
        String algorithm = "HmacSHA256";

        String hashKey = "some_key";
        String message = "abcdefg";

        String hexed = "";

        try {
            Mac sha256_HMAC = Mac.getInstance(algorithm);
            SecretKeySpec secret_key = new SecretKeySpec(hashKey.getBytes(), algorithm);
            sha256_HMAC.init(secret_key);

            byte[] hash = sha256_HMAC.doFinal(message.getBytes("UTF-8"));

            // it doesn't work for me.
//            hexed = new String(hash, "UTF-8");

            // it works.
            hexed = bytesToHex(hash);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return hexed;
    }

    public static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
    public static String bytesToHex(final byte[] data ) {
        final int l = data.length;
        final char[] hexChars = new char[l<<1];
        for( int i=0, j =0; i < l; i++ ) {
            hexChars[j++] = HEX_DIGITS[(0xF0 & data[i]) >>> 4];
            hexChars[j++] = HEX_DIGITS[0x0F & data[i]];
        }
        return new String(hexChars);
    }

Thanks.

3 Answers 3

4

Following is a sample which shows Conversion of Byte array to String :-

public class TestByte
{    
public static void main(String[] argv) {

        String example = "This is an example";
        byte[] bytes = example.getBytes();

        System.out.println("Text : " + example);
        System.out.println("Text [Byte Format] : " + bytes);
        System.out.println("Text [Byte Format] : " + bytes.toString());

        String s = new String(bytes);
        System.out.println("Text Decryted : " + s);
     }}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure the string you get in the end is what you're after. I think a common scenario is to use

new BASE64Encoder().encode(hash)

which will return you the hashed message as String.

Comments

-2

just do new String(byteArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.