Generating a base64 encoded hash from CLI to match Java

一曲冷凌霜 提交于 2019-11-29 23:58:51

问题


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 guessing the problem with what I am doing here is with the character set / encoding or to do with converting the string to a byte array. Java code:

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] digest = md.digest("testString".getBytes());
// ^^ this is where the difference is?
String b64url = Base64.encodeBase64URLSafeString(digest);
// b64url: Ss8LOdnEdmcJo2ifVTrAGrVQVF_6RUTfwLLOqC-6AqM

Command line:

echo testString | sha256sum | cut -d" " -f1 | base64
# NDgxOGEyY2JkODYwOTY1NjJkODFmYzIwNmQ3ZTYyNWVlNGFjMTU5MmViNTc0MjQwMDQ4OTIzOTBl
# MDQzZTNlYwo=

Is it possible to generate base64 encoded sha256 via cli tools?


回答1:


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



回答2:


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 ...



来源:https://stackoverflow.com/questions/12708732/generating-a-base64-encoded-hash-from-cli-to-match-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!