gpt4 book ai didi

java - 在java中将字节数组转换为字符串

转载 作者:行者123 更新时间:2023-12-02 03:55:13 24 4
gpt4 key购买 nike

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

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

通过将十六进制代码转换为基本字符数组,我终于获得了有效的字符串数组。像这样。 ojit_代码

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

这是方法。字节数组,当我散列时,它由 char[] chars = {"0", "1", ... "e", "f"}; 使用特定键进行散列。

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

谢谢。

最佳答案

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

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

关于java - 在java中将字节数组转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35553334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com