Checksum calculation extensions for Swift
Extends String
, Data
, and URL
adding the ability to easily and efficiently calculate the cryptographic checksum of its associated
contents by adding conformance to the Checksumable
protocol.
Under the hood, Apple's CommonCrypto
framework is used.
MD5
, SHA1
, SHA224
, SHA256
, SHA384
, SHA512
Processing and progress monitoring are performed asynchronously on a background dispatch queue. Progress and completion
closures are, by default, called on the .main
dispatch queue. However, a different DispatchQueue
may be specified.
The function signature for async processing is:
checksum(algorithm:chunkSize:queue:progress:completion:)
In the cases where the payload is fairly small, asynchronous processing may not be required or desirable. For such cases, a synchronous version is provided.
The function signature for sync processing is:
checksum(algorithm:chunkSize:)
Any URLs with schemes file
, http
, or https
may be used as input. However, http
and https
support is currently experimental and has the following requirements:
HEAD
requests in order to determine whether the URL
is reachable.Support for processing arrays of Checksumable
items is also included and showcased in the examples below.
Data
asynchronouslydata.checksum(algorithm: .md5) { result in
switch result {
case .success(let checksum):
// Use checksum
case .failure(let error):
// Unable to obtain checksum
}
}
URL
asynchronouslyremoteURL.checksum(algorithm: .sha256) { result in
switch result {
case .success(let checksum):
// Use checksum
case .failure(let error):
// Unable to obtain checksum
}
}
URLs
asynchronously[someURL, anotherURL, yetAnotherURL].checksum(algorithm: .md5) { result in
switch result {
case .success(let checksumResults):
// Use results object
for checksumResult in checksumResults {
guard let url = checksumResult.checksumable as? URL else {
fail("Expected checksumable to be of type URL.")
return
}
if let checksum = checksumResult.checksum {
print("Checksum of \(result.checksumable) is \(checksumResult.checksum)")
} else {
print("Unable to obtain checksum for \(checksumResult.checksumable)")
}
}
case .failure(let error):
// Unable to obtain checksums
}
}
String
synchronouslyif let checksum = string.checksum(algorithm: .md5) {
// Use checksum
}
Data
synchronouslyif let checksum = data.checksum(algorithm: .md5) {
// Use checksum
}
URL
synchronouslyif let checksum = localURL.checksum(algorithm: .md5) {
// Use checksum
}
You may monitor progress by passing a ProgressHandler
closure to the progress
argument in
checksum(algorithm:chunkSize:queue:progress:completion:)
.
remoteURL.checksum(algorithm: .sha256, progress: { progress in
// Add your progress handling code here.
print("Fraction completed: \(progress.fractionCompleted)")
}) { result in
/// Result handling ommited.
}
Checksum
was written by Ruben Nine (@sonicbee9) and is licensed under the
MIT license. See LICENSE.md.