简体   繁体   English

getBytes() 在 Windows (Java9) 下按预期工作,在 Linux 下也不工作

[英]getBytes() works as expected under Windows (Java9) and does nor works under Linux

Method getBytes() works as expected under Windows (Java9) and does nor works under Linux.方法 getBytes() 在 Windows (Java9) 下按预期工作,在 Linux 下也不工作。 Characterset() => UTF-8 on both systems. Characterset() => UTF-8 在两个系统上。 JVM Version => Java 9 (I tested open jvm and oracle jvm under Linux) JVM Version => Java 9 (I tested open jvm and oracle jvm under Linux)
Code:代码:

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

the same under Windows and Linux.在 Windows 和 Linux 下相同。 I also tested compiling and export executable JAR under windows and rut it on Linux, all functionality works fine except code above.我还测试了在 windows 下编译和导出可执行文件 JAR 并在 Linux 上运行它,除上述代码外,所有功能都可以正常工作。

Please remember always use the charset, this avoid unexpected results.请记住始终使用字符集,这样可以避免意外结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM