首页 > 解决方案 > 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 上运行它,除了上面的代码之外,所有功能都可以正常工作。

标签: javalinuxencodingbase64

解决方案


请记住始终使用字符集,这样可以避免意外结果。

new SecretKeySpec(secret.getBytes ( Charsets.UTF_8 ), ALGORITHM)

推荐阅读