在Java和Swift中计算sha256时,它不匹配。
爪哇语:
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]
它以相同的值开始,但随后开始不同
最佳答案
Bytes in Java are signed,因此它们只能表示-128到127的值,因此当它试图表示225(第三个字节)时,它会溢出到-31。两个字节的实际二进制表示将相同。
关于java - Java sha256与Swift sha256不匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46644816/