从 CLI 生成 base64 编码哈希以匹配 Java [英] Generating a base64 encoded hash from CLI to match Java

查看:40
本文介绍了从 CLI 生成 base64 编码哈希以匹配 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 java 代码库,可以从字符串生成 URL 安全的 base64 编码哈希,我想知道这是否/如何使用 linux 命令行工具实现.我猜我在这里所做的问题与字符集/编码有关,或者与将字符串转换为字节数组有关.Java 代码:

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

命令行:

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

是否可以通过cli工具生成base64编码的sha256?

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

推荐答案

你是base64编码一个十六进制字符串,而不是hash的字节值,相当于:

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

这篇关于从 CLI 生成 base64 编码哈希以匹配 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆