diff --git a/Sources/TSCBasic/HashAlgorithms.swift b/Sources/TSCBasic/HashAlgorithms.swift index 422498da..dc3ec9f8 100644 --- a/Sources/TSCBasic/HashAlgorithms.swift +++ b/Sources/TSCBasic/HashAlgorithms.swift @@ -8,6 +8,10 @@ See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ +#if canImport(CryptoKit) +import CryptoKit +#endif + public protocol HashAlgorithm { /// Hashes the input bytes, returning the digest. @@ -169,6 +173,24 @@ public struct SHA256: HashAlgorithm { } } +/// Wraps CryptoKit.SHA256 to provide a HashAlgorithm conformance to it. +@available(macOS 10.15, *) +public struct CryptoKitSHA256: HashAlgorithm { + public init() { + } + + public func hash(_ bytes: ByteString) -> ByteString { + #if canImport(CryptoKit) + return bytes.withData { data in + let digest = CryptoKit.SHA256.hash(data: data) + return ByteString(digest) + } + #else + fatalError("not supported on this platform") + #endif + } +} + // MARK:- Helpers private extension UInt64 { diff --git a/Tests/TSCBasicTests/SHA256Tests.swift b/Tests/TSCBasicTests/SHA256Tests.swift index 6a3e2974..17133ad2 100644 --- a/Tests/TSCBasicTests/SHA256Tests.swift +++ b/Tests/TSCBasicTests/SHA256Tests.swift @@ -43,4 +43,15 @@ class SHA256Tests: XCTestCase { let digest = SHA256().hash(ByteString(data)).hexadecimalRepresentation XCTAssertEqual(digest, "907422e2f24d749d0add2b504ccae8ad1aa392477591905880fb2dc494e33d63") } + + #if os(macOS) + @available(macOS 10.15, *) + func testCryptoKitSHA256() { + let sha = CryptoKitSHA256() + XCTAssertEqual( + sha.hash(ByteString("The quick brown fox jumps over the lazy dog")).hexadecimalRepresentation, + "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592" + ) + } + #endif }