Skip to content

Commit cffd634

Browse files
authored
Merge pull request #31 from hartbit/crypto-sha256
HashAlgorithm conformance that wraps CryptoKit.SHA256
2 parents 45d36ae + f34f419 commit cffd634

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

Sources/TSCBasic/HashAlgorithms.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@
88
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
99
*/
1010

11+
#if canImport(CryptoKit)
12+
import CryptoKit
13+
#endif
14+
1115
public protocol HashAlgorithm {
1216

1317
/// Hashes the input bytes, returning the digest.
@@ -169,6 +173,24 @@ public struct SHA256: HashAlgorithm {
169173
}
170174
}
171175

176+
/// Wraps CryptoKit.SHA256 to provide a HashAlgorithm conformance to it.
177+
@available(macOS 10.15, *)
178+
public struct CryptoKitSHA256: HashAlgorithm {
179+
public init() {
180+
}
181+
182+
public func hash(_ bytes: ByteString) -> ByteString {
183+
#if canImport(CryptoKit)
184+
return bytes.withData { data in
185+
let digest = CryptoKit.SHA256.hash(data: data)
186+
return ByteString(digest)
187+
}
188+
#else
189+
fatalError("not supported on this platform")
190+
#endif
191+
}
192+
}
193+
172194
// MARK:- Helpers
173195

174196
private extension UInt64 {

Tests/TSCBasicTests/SHA256Tests.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,15 @@ class SHA256Tests: XCTestCase {
4343
let digest = SHA256().hash(ByteString(data)).hexadecimalRepresentation
4444
XCTAssertEqual(digest, "907422e2f24d749d0add2b504ccae8ad1aa392477591905880fb2dc494e33d63")
4545
}
46+
47+
#if os(macOS)
48+
@available(macOS 10.15, *)
49+
func testCryptoKitSHA256() {
50+
let sha = CryptoKitSHA256()
51+
XCTAssertEqual(
52+
sha.hash(ByteString("The quick brown fox jumps over the lazy dog")).hexadecimalRepresentation,
53+
"d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
54+
)
55+
}
56+
#endif
4657
}

0 commit comments

Comments
 (0)