在Java和Swift中計算sha256時,它不匹配。Java sha256不匹配Swift sha256
的Java:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(secretKey.getBytes("UTF-8"));
byte[] secretKeyBytes = secretKey.getBytes("UTF-8");
byte[] keyBytes = new byte[16];
System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
結果:[44, 112, -31, 43, 122, 6, 70, -7, 34, 121, -12, 39, -57, -77, -114, 115]
斯威夫特:
let secretKeyBytes = [UInt8](secretKey.utf8)
var digest = SHA2(variant: SHA2.Variant.sha256)
try digest.update(withBytes: secretKeyBytes)
let keyDigest = try digest.finish()
let keyBytes = Array(keyDigest[0...15])
結果:[44, 112, 225, 43, 122, 6, 70, 249, 34, 121, 244, 39, 199, 179, 142, 115]
它始於相同的值,但隨後開始不同
您的Java代碼溢出併產生負值。 – the4kman
[SHA256散列結果在Android和iOS中對於大數字有不同的結果](https://stackoverflow.com/questions/39018731/sha256-hash-results-different-across-android-ios-for-big-numbers) – pedrofb