gpt4 book ai didi

java - 将负值的 byte[] 转换为 String

转载 作者:行者123 更新时间:2023-12-02 09:21:49 25 4
gpt4 key购买 nike

我有这个字节[] = {-53, 54, -5, -89, -69, -126, -57, 36, 49, 114, -66, 67, 39, 18, 57, -40 , 50, -113, 52, -113, 111, -65, -20, -127, -84, 90, -74, -47, 94, 23, 18, -36}

如何将其转换为字符串?我尝试了很多方法,但都不起作用

我正在使用这个库来编码我的字符串 https://github.com/scottyab/AESCrypt-Android ,上面有几行代码生成byte[]

private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
byte[] bytes = password.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
byte[] key = digest.digest(); //I want to convert this byte[] to String

log("SHA-256 key ", key);

SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
return secretKeySpec;
}

最佳答案

您应该使用 Base64 对字节数组进行编码。

如果您使用Java8,Base64已经包含在java.util包中。

尝试以下代码:

 public static void main(String args[]) throws IOException {

byte[] b = {-53, 54, -5, -89, -69, -126, -57, 36, 49, 114, -66, 67, 39, 18, 57, -40, 50, -113, 52, -113, 111, -65, -20, -127, -84, 90, -74, -47, 94, 23, 18, -36};
String encoded = Base64.getEncoder().encodeToString(b);
System.out.println(encoded);

}

结果:

  yzb7p7uCxyQxcr5DJxI52DKPNI9vv+yBrFq20V4XEtw=

关于java - 将负值的 byte[] 转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58641411/

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