gpt4 book ai didi

java - SHA256 : different output in Swift and Java?

转载 作者:行者123 更新时间:2023-11-28 15:25:00 25 4
gpt4 key购买 nike

我正在尝试使用 SHA256 对字符串进行编码。我知道输出应该是什么样子。这是我从一个有效的 Java 中得到的:

string = "1234nonce=1234"

SHA256 Hash from string in Java:

string.digest() =
[-29, -80, -60, 66, -104, -4, 28, 20, -102, -5, -12, -56, -103, 111,
-71, 36, 39, -82, 65, -28, 100, -101, -109, 76, -92, -107, -103, 27,
120, 82, -72, 85]

现在我需要在 Swift 中获得相同的结果:

 func sha256() {
let string = "1234nonce=1234"
let intArray = [UInt8](string.utf8)
let data = Data(bytes: intArray)

var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(data.count), &hash)
}
print(hash)
return Data(bytes: hash)
}

但是结果是这样的:

[218, 207, 142, 73, 87, 235, 210, 73, 201, 67, 19, 33, 57, 146, 69, 48, 51, 56, 0, 212, 172, 114, 118, 31, 102, 19, 175, 51, 153, 230, 143, 67]

Java中第一个结果是如何产生的,可以看here在最后的答案中。(那里,nonce + data 对应于 "1234nonce=1234")我想知道我是否做错了什么。非常感谢任何形式的帮助。

最佳答案

简答

看来您使用 Swift 语言实现的 SHA-256 哈希算法是正确的。

长答案

The Java example you are referring to不仅包含SHA-256哈希算法实现,还包含计算签名的HMAC-SHA-512算法实现(?)。

总而言之,如果只需要 SHA-256 算法,请检查以下 draft Java 实现:

package com.thecompany.test;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Program {
public static void main(final String[] args) throws NoSuchAlgorithmException {
// Input.
final String input = "1234nonce=1234";

// Processing.
final byte[] output = sha256(input);

// Output.
System.out.printf("Signed output: %s.%n", Arrays.toString(output));

final List<Integer> unsignedOutput = unsignedIntStream(output)
.boxed()
.collect(Collectors.toList());
System.out.printf("Unsigned output: %s.%n", unsignedOutput);
}

private static IntStream unsignedIntStream(final byte[] array) {
return IntStream
.range(0, array.length)
.map(index -> Byte.toUnsignedInt(array[index]));
}

private static byte[] sha256(final String text) throws NoSuchAlgorithmException {
final MessageDigest digest = MessageDigest.getInstance("SHA-256");
return digest.digest(text.getBytes(StandardCharsets.UTF_8));
}
}

程序产生以下输出:

Signed output: [-38, -49, -114, 73, 87, -21, -46, 73, -55, 67, 19, 33, 57, -110, 69, 48, 51, 56, 0, -44, -84, 114, 118, 31, 102, 19, -81, 51, -103, -26, -113, 67].
Unsigned output: [218, 207, 142, 73, 87, 235, 210, 73, 201, 67, 19, 33, 57, 146, 69, 48, 51, 56, 0, 212, 172, 114, 118, 31, 102, 19, 175, 51, 153, 230, 143, 67].

希望这对您有所帮助。

关于java - SHA256 : different output in Swift and Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45394304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com