Created
October 22, 2018 05:34
-
-
Save crspybits/e43c68cffe74de27f0a157006c1220e6 to your computer and use it in GitHub Desktop.
Create Dropbox Content Hash in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CommonCrypto is only available with Xcode 10 for import into Swift; see also https://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework | |
import CommonCrypto | |
class Hashing { | |
// From https://stackoverflow.com/questions/25388747/sha256-in-swift | |
private static func sha256(data : Data) -> Data { | |
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) | |
data.withUnsafeBytes { | |
_ = CC_SHA256($0, CC_LONG(data.count), &hash) | |
} | |
return Data(bytes: hash) | |
} | |
// Method: https://www.dropbox.com/developers/reference/content-hash | |
static func generateDropbox(fromLocalFile localFile: URL) -> String? { | |
let blockSize = 1024 * 1024 * 4 | |
guard let inputStream = InputStream(url: localFile) else { | |
print("Error opening input stream: \(localFile)") | |
return nil | |
} | |
var inputBuffer = [UInt8](repeating: 0, count: blockSize) | |
inputStream.open() | |
defer { | |
inputStream.close() | |
} | |
var concatenatedSHAs = Data() | |
while true { | |
let length = inputStream.read(&inputBuffer, maxLength: blockSize) | |
if length == 0 { | |
// EOF | |
break | |
} | |
else if length < 0 { | |
return nil | |
} | |
let dataBlock = Data(bytes: inputBuffer, count: length) | |
let sha = sha256(data: dataBlock) | |
concatenatedSHAs.append(sha) | |
} | |
let finalSHA = sha256(data: concatenatedSHAs) | |
let hexString = finalSHA.map { String(format: "%02hhx", $0) }.joined() | |
return hexString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment