replace Cryptography.computeSHA256Digest with CryptoKit.SHA256.hash(data:)

This commit is contained in:
Ehren Kret 2024-08-02 14:39:10 -05:00
parent 897d2441f5
commit 3f04087244
12 changed files with 25 additions and 121 deletions

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import GRDB
import Intents
import SignalServiceKit
@ -47,7 +48,7 @@ private func uncaughtExceptionHandler(_ exception: NSException) {
} else {
let reason = exception.reason ?? ""
let reasonData = reason.data(using: .utf8) ?? Data()
let reasonHash = Cryptography.computeSHA256Digest(reasonData)?.base64EncodedString() ?? ""
let reasonHash = Data(SHA256.hash(data: reasonData)).base64EncodedString()
var truncatedReason = reason.prefix(20)
if let spaceIndex = truncatedReason.lastIndex(of: " ") {

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import Foundation
import MultipeerConnectivity
import SignalServiceKit
@ -359,9 +360,7 @@ extension DeviceTransferService: MCSessionDelegate {
let certificateData = SecCertificateCopyData(certificate as! SecCertificate) as Data
// Reject any connections where we can't compute the certificate hash
guard let certificateHash = Cryptography.computeSHA256Digest(certificateData) else {
return owsFailDebug("failed to calculate certificate hash")
}
let certificateHash = Data(SHA256.hash(data: certificateData))
// Reject any connections where the certificate doesn't match the expected certificate
guard expectedCertificateHash.ows_constantTimeIsEqual(to: certificateHash) else {

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import Foundation
import MultipeerConnectivity
import SignalServiceKit
@ -77,7 +78,7 @@ class DeviceTransferService: NSObject {
static let databaseWALIdentifier = "database-wal"
static let missingFileData = "Missing File".data(using: .utf8)!
static let missingFileHash = Cryptography.computeSHA256Digest(missingFileData)!
static let missingFileHash = Data(SHA256.hash(data: missingFileData))
// This must also be updated in the info.plist
private static let newDeviceServiceIdentifier = "sgnl-new-device"

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import LibSignalClient
import SignalServiceKit
@ -110,11 +111,6 @@ extension SecIdentity {
}
let certificateData = SecCertificateCopyData(certificate) as Data
guard let hash = Cryptography.computeSHA256Digest(certificateData) else {
throw OWSAssertionError("failed to compute certificate hash")
}
return hash
return Data(SHA256.hash(data: certificateData))
}
}

View File

@ -4,6 +4,7 @@
//
import Contacts
import CryptoKit
import Foundation
import LibSignalClient
@ -579,11 +580,7 @@ extension OWSContactsManager: ContactManager {
guard let contactAvatarData = avatarData(for: cnContactId) else {
return nil
}
guard let contactAvatarHash = Cryptography.computeSHA256Digest(contactAvatarData) else {
owsFailDebug("Could not digest contactAvatarData.")
return nil
}
return contactAvatarHash
return Data(SHA256.hash(data: contactAvatarData))
}
}

View File

@ -16,22 +16,6 @@ public enum Cryptography {
return try digestContext.finalize()
}
public static func computeSHA256Digest(_ data: Data) -> Data? {
var digestContext = Sha256DigestContext()
do {
try digestContext.update(data)
return try digestContext.finalize()
} catch {
owsFailDebug("Failed to compute digest \(error)")
return nil
}
}
static func computeSHA256Digest(_ data: Data, truncatedToBytes: UInt) -> Data? {
guard let digest = computeSHA256Digest(data), digest.count >= truncatedToBytes else { return nil }
return digest.subdata(in: digest.startIndex..<digest.startIndex.advanced(by: Int(truncatedToBytes)))
}
static func computeSHA256HMAC(_ data: Data, key: Data) -> Data? {
do {
var context = HmacContext(key: key)

View File

@ -17,54 +17,6 @@ class CryptographyTestsSwift: XCTestCase {
XCTAssertNotEqual(paddedSize, Cryptography.paddedSize(unpaddedSize: unpaddedSize), file: file, line: line)
}
func test_computeSha256Digest() throws {
let plaintext = "SGF3YWlpIGlzIEF3ZXNvbWUh"
let plaintextData = try XCTUnwrap(Data(base64Encoded: plaintext, options: .ignoreUnknownCharacters))
let digest = Cryptography.computeSHA256Digest(plaintextData)
let expectedBytes: [UInt8] = [
0xba,
0x5f,
0xf1,
0x26,
0x82,
0xbb,
0xb2,
0x51,
0x8b,
0xe6,
0x06,
0x48,
0xc5,
0x53,
0xd0,
0xa2,
0xbf,
0x71,
0xf1,
0xec,
0xb4,
0xdb,
0x02,
0x12,
0x5f,
0x80,
0xea,
0x34,
0xc9,
0x8d,
0xee,
0x1f,
]
let expectedDigest = Data(bytes: expectedBytes, count: expectedBytes.count)
XCTAssertEqual(expectedDigest, digest)
let truncatedLength = 10
let expectedTruncatedDigest = Data(bytes: expectedBytes, count: truncatedLength)
let truncatedDigest = try XCTUnwrap(Cryptography.computeSHA256Digest(plaintextData, truncatedToBytes: UInt(truncatedLength)))
XCTAssertEqual(expectedTruncatedDigest, truncatedDigest)
}
func test_paddedSizeSpotChecks() {
Assert(unpaddedSize: 1, hasPaddedSize: 541)
Assert(unpaddedSize: 12, hasPaddedSize: 541)

View File

@ -4,6 +4,7 @@
//
import AudioToolbox
import CryptoKit
public enum Sound: Equatable {
case standard(StandardSound)
@ -219,16 +220,8 @@ public struct CustomSound {
let id: UInt
let filename: String
private init(id: UInt, filename: String) {
self.id = id
self.filename = filename
}
init?(filename: String) {
guard let id = CustomSound.idFromFilename(filename) else {
return nil
}
self.id = id
init(filename: String) {
self.id = CustomSound.idFromFilename(filename)
self.filename = filename
}
@ -265,19 +258,10 @@ public struct CustomSound {
private static let customSoundShift: UInt = 16
private static func idFromFilename(_ filename: String) -> UInt? {
guard let filenameData = filename.data(using: .utf8) else {
owsFailDebug("could not get data from filename.")
return nil
}
guard let hashData = Cryptography.computeSHA256Digest(filenameData, truncatedToBytes: UInt(MemoryLayout<UInt>.size)) else {
owsFailDebug("could not get hash from filename.")
return nil
}
var hashValue: UInt = 0
hashData.withUnsafeBytes { ptr in
hashValue = ptr.load(as: UInt.self)
private static func idFromFilename(_ filename: String) -> UInt {
let filenameData = Data(filename.utf8)
let hashValue = Data(SHA256.hash(data: filenameData)).prefix(MemoryLayout<UInt>.size).withUnsafeBytes {
$0.loadUnaligned(as: UInt.self)
}
return hashValue << customSoundShift
}

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import Foundation
import LibSignalClient
@ -324,11 +325,7 @@ public extension TSGroupModel {
}
class func hash(forAvatarData avatarData: Data) throws -> String {
guard let digest = Cryptography.computeSHA256Digest(avatarData) else {
throw OWSAssertionError("Unexpectedly failed to calculate avatar digest")
}
return digest.hexadecimalString
return Data(SHA256.hash(data: avatarData)).hexadecimalString
}
var avatarData: Data? {

View File

@ -4,6 +4,7 @@
//
import AVFoundation
import CryptoKit
import Foundation
public class AttachmentContentValidatorImpl: AttachmentContentValidator {
@ -721,10 +722,7 @@ public class AttachmentContentValidatorImpl: AttachmentContentValidator {
private func computePlaintextHash(input: Input) throws -> Data {
switch input {
case .inMemory(let data):
guard let hash = Cryptography.computeSHA256Digest(data) else {
throw OWSAssertionError("Couldn't compute plaintext hash")
}
return hash
return Data(SHA256.hash(data: data))
case .unencryptedFile(let fileUrl):
return try Cryptography.computeSHA256DigestOfFile(at: fileUrl)
case .encryptedFile(let fileUrl, let encryptionKey, let plaintextLength, _):

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import LibSignalClient
public enum IdentityManagerError: Error, IsRetryableProvider {
@ -981,10 +982,7 @@ public class OWSIdentityManagerImpl: OWSIdentityManager {
guard let identityKey = try? self.identityKey(for: serviceId, tx: tx) else { return nil }
let externalIdentityKey = identityKey.serialize().asData
guard let identityKeyDigest = Cryptography.computeSHA256Digest(externalIdentityKey) else {
owsFailDebug("Failed to calculate SHA-256 digest for batch identity key update")
return nil
}
let identityKeyDigest = Data(SHA256.hash(data: externalIdentityKey))
return ["uuid": serviceId.serviceIdString, "fingerprint": Data(identityKeyDigest.prefix(4)).base64EncodedString()]
}

View File

@ -3,6 +3,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
//
import CryptoKit
import Foundation
import LibSignalClient
@ -405,11 +406,7 @@ public class RemoteConfig: NSObject {
data.append(Data(aci.serviceIdBinary))
guard let hash = Cryptography.computeSHA256Digest(data) else {
owsFailDebug("Failed to calculate hash")
return 0
}
let hash = Data(SHA256.hash(data: data))
guard hash.count == 32 else {
owsFailDebug("Hash has incorrect length \(hash.count)")
return 0