Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create Dropbox Content Hash in Swift on iOS
// 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 {
Log.msg("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
You can’t perform that action at this time.