方法 getBytes() 在 Windows (Java9) 下按预期工作,但在 Linux 下不起作用。两个系统上的Characterset() => UTF-8。 JVM版本=>Java 9(我在Linux下测试了open jvm和oracle jvm)
代码:
public static String createSign(String uri, String apiSecret) throws UnsupportedEncodingException{
byte[] signBytes = calculateSignBytes(uri, apiSecret);
return bytesToHexString(signBytes);
}
private static byte[] calculateSignBytes(String uri, String secret) throws UnsupportedEncodingException {
try {
Mac mac = Mac.getInstance(ALGORITHM);
SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(), ALGORITHM);
mac.init(secretKeySpec);
return mac.doFinal(uri.getBytes());
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException(e);
}
}
private static String bytesToHexString(byte[] bytes){
StringBuilder stringBuilder = new StringBuilder();
for (byte b : bytes) {
stringBuilder.append(String.format("%02x", b));
}
return stringBuilder.toString();
}
Windows和Linux下相同。我还在 Windows 下测试了编译和导出可执行 JAR,并在 Linux 上测试了它,除了上面的代码之外,所有功能都运行良好。
最佳答案
请记住始终使用字符集,这样可以避免意外结果。
new SecretKeySpec(secret.getBytes ( Charsets.UTF_8 ), ALGORITHM)
关于java - getBytes() 在 Windows (Java 9) 下按预期工作,但在 Linux 下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58381977/