Skip to content

Commit 0bd6a54

Browse files
committed
Add sha256Checksum property to ByteString in extension
1 parent b1a6f45 commit 0bd6a54

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
This source file is part of the Swift.org open source project
3+
Copyright (c) 2020 Apple Inc. and the Swift project authors
4+
Licensed under Apache License v2.0 with Runtime Library Exception
5+
See http://swift.org/LICENSE.txt for license information
6+
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
7+
*/
8+
9+
import TSCBasic
10+
11+
extension ByteString {
12+
/// A lowercase, hexadecimal representation of the SHA256 hash
13+
/// generated for the byte string's contents.
14+
///
15+
/// This property uses the CryptoKit implementation of
16+
/// Secure Hashing Algorithm 2 (SHA-2) hashing with a 256-bit digest, when available,
17+
/// falling back on a native implementation in Swift provided by TSCBasic.
18+
public var sha256Checksum: String {
19+
#if canImport(CryptoKit)
20+
if #available(macOS 10.15, *) {
21+
return CryptoKitSHA256().hash(self).hexadecimalRepresentation
22+
}
23+
#endif
24+
25+
return SHA256().hash(self).hexadecimalRepresentation
26+
}
27+
}

Sources/Basics/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
# See http://swift.org/CONTRIBUTORS.txt for Swift project authors
88

99
add_library(Basics
10+
ByteString+Extensions.swift
1011
ConcurrencyHelpers.swift
1112
Dictionary+Extensions.swift
1213
DispatchTimeInterval+Extensions.swift
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
This source file is part of the Swift.org open source project
3+
4+
Copyright (c) 2020 Apple Inc. and the Swift project authors
5+
Licensed under Apache License v2.0 with Runtime Library Exception
6+
7+
See http://swift.org/LICENSE.txt for license information
8+
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
9+
*/
10+
11+
import Basics
12+
import TSCBasic
13+
import XCTest
14+
15+
final class ByteStringExtensionsTests: XCTestCase {
16+
func testSHA256Checksum() {
17+
let byteString = ByteString(encodingAsUTF8: "abc")
18+
XCTAssertEqual(byteString.contents, [0x61, 0x62, 0x63])
19+
20+
// See https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/examples/sha_all.pdf
21+
XCTAssertEqual(byteString.sha256Checksum, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
22+
}
23+
}

0 commit comments

Comments
 (0)