File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change 88 See http://swift.org/CONTRIBUTORS.txt for Swift project authors
99*/
1010
11+ #if canImport(CryptoKit)
12+ import CryptoKit
13+ #endif
14+
1115public 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
174196private extension UInt64 {
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments