在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]
它以相同的值开始但后来开始不同
答案 0 :(得分:5)
Bytes in Java are signed,因此它们只能表示-128到127的值,因此当它试图表示溢出到-31的225(第三个字节)时。两个字节的实际二进制表示将是相同的EPERM
。