java - getBytes() 在 Windows (Java9) 下按预期工作,在 Linux 下也不工作
问题描述
方法 getBytes() 在 Windows (Java9) 下按预期工作,在 Linux 下也不工作。Characterset() => 两个系统上的 UTF-8。JVM Version => 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)
推荐阅读
- mysql - 选择具有相同外键但另一列具有一组值的行
- variadic-functions - 什么是 ... 语法上的可变参数?
- android - 通过 runBlocking kotlin 阻塞 Application 类
- docker - Windows 镜像的 Docker 镜像
- css - 为什么我的线性渐变对我的图像不起作用?
- javascript - 提交到 Facebook Pixel 的 Javascript 函数未触发点击
- android - 我的应用程序是否可以请求使用第三方应用程序资源的权限,而不是基本的 android 应用程序
- digital-signature - 部署 CorDapp 时,JAR 必须默认签名吗?
- android - 有没有一种方法可以使用来自云 Firestore 的数据设置 textformfield 的初始值,而无需将显示的数据括在大括号中?
- c# - 在 Winform 中使用 ffplay/ffmpeg 渲染多个 Gif