我正在尝试将一个库转换为java。我被困在一个地方。
节点js中的此方法
import { SHA256, enc } from 'crypto-js'
export const sha256 = (hex) => {
let hexEncoded = enc.Hex.parse(hex)
return SHA256(hexEncoded).toString()
}
你能帮我把它转换成java吗?这不是直接的sha256加密。例如:
Direct conversion :
String : 68656c6c6f
Sha256 string : 4ef79bf561cdeacd465e135a3b9c8b51a42ded0605f15ab8e501162d2693bd00
来源:http://md5decrypt.net/en/Sha256/#answer
上述方法转换
String : 68656c6c6f
Sha256 String : 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
我不确定我漏掉了哪部分。第一步是把它转换成十进制的,第二个step.This中的逻辑是从array.But -js库中取出来的。(https://www.npmjs.com/package/crypto-js)
发布于 2018-07-30 04:50:24
String : 68656c6c6f
基本上是十六进制的字符串hello
和
Sha256 String : 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
是hello
的sha256哈希
因此,首先您需要解析十六进制字符串,即->
68656c6c6f -> hello
然后计算sha256散列:->
hello -> 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
同样的Java实现:->
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import java.nio.charset.StandardCharsets;
public class libraryTransfer {
public static void main(String[] args) throws DecoderException {
String input = "hello";
System.out.println("Hex from String :-> " + toHex(input));
System.out.println("String from hex : -> " + getStringFromHex(toHex(input.trim())).trim());
String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(getStringFromHex(toHex(input)));
System.out.println(sha256hex);
}
public static String toHex(String arg) {
return Hex.encodeHexString(arg.getBytes(/* charset */));
}
public static String getStringFromHex(String inputHex) throws DecoderException {
byte[] bytes = Hex.decodeHex(inputHex.toCharArray());
return new String(bytes, StandardCharsets.UTF_8);
}
}
https://stackoverflow.com/questions/51583713
复制相似问题