Generating a base64 encoded hash from CLI to match Java

后端 未结 2 453
深忆病人
深忆病人 2021-01-03 16:08

I have a java code base that generates an URL safe base64 encoded hash from a string, and wondering if / how this would be possible with linux command line tools. I\'m guess

相关标签:
2条回答
  • 2021-01-03 16:38

    You can use a StringBuilder to turn your hex into a meaningful string:

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    byte[] digest = md.digest("testString".getBytes());
    StringBuilder sb = new StringBuuilder();
    for (byte b : digest) {
        sb.append(Integer.toHexString(b & 0xff));
    }
    String base64 = Base64.encodeBase64(sb.toString());
    

    Combined with not including the newline in the echo command, works here ...

    0 讨论(0)
  • 2021-01-03 16:51

    You're base64 encoding a hexadecimal string, not the byte values of the hash, which is the equivalent of:

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    byte[] digest = md.digest("testString".getBytes()); // Missing charset
    String hex = Hex.encodeHexString(digest);
    String base64 = Base64.encodeBase64(hex.getBytes());
    
    0 讨论(0)
提交回复
热议问题