Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Sources/TSCBasic/HashAlgorithms.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
11 changes: 11 additions & 0 deletions Tests/TSCBasicTests/SHA256Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}