【问题标题】:convert byte array to string in java在java中将字节数组转换为字符串
【发布时间】:2016-06-03 20:40:11
【问题描述】:

我尝试使用new String( bytes, "UTF-8") 方法将字节数组转换为java 中的字符串,但它们只返回对象。像这样@AB4634bSbbfa

所以,我搜索了一些方法来解决这个问题。

通过将十六进制代码转换为基本字符数组,我终于得到了有效的字符串数组。 像这样。 char[] chars = {"0", "1", ... "e", "f"};

这在以前从未发生过,为什么我必须转换十六进制代码才能获得有效的字符串。

这里是方法。 字节数组,当我散列时由Mac-sha-256 用特定键散列。

    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);
    }

谢谢。

【问题讨论】:

    标签: java android string sha256 string-hashing


    【解决方案1】:

    以下是一个示例,它显示了字节数组到字符串的转换:-

    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);
         }}
    

    【讨论】:

      【解决方案2】:

      我不确定你最后得到的字符串是你想要的。我认为一个常见的场景是使用

      new BASE64Encoder().encode(hash)

      这会将散列消息作为字符串返回给您。

      【讨论】:

        【解决方案3】:

        只做 new String(byteArray);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-06
          • 2013-12-19
          • 2011-07-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多