Skip to content

Instantly share code, notes, and snippets.

@RobJDavey
Last active June 26, 2023 12:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobJDavey/d031aca84608da1495d978ff7cfccecc to your computer and use it in GitHub Desktop.
Save RobJDavey/d031aca84608da1495d978ff7cfccecc to your computer and use it in GitHub Desktop.
Using CommonCrypto in a Swift Script
#include <CommonCrypto/CommonCrypto.h>
#include <CommonCrypto/CommonRandom.h>
module CommonCrypto [system] {
header "common-crypto.h"
export *
}
#!/usr/bin/env swift -I /usr/local/include
import CommonCrypto
import Foundation
extension NSData {
var hex: String {
var result = ""
let buffer = UnsafeMutablePointer<UInt8>(bytes)
for i in 0..<length {
result += NSString(format: "%02x", buffer[i]) as String
}
return result
}
}
func sha1(url: NSURL) -> String? {
guard let inputStream = NSInputStream(URL: url) else {
return nil
}
defer {
inputStream.close()
}
inputStream.open()
var ctx = CC_SHA1_CTX()
CC_SHA1_Init(&ctx)
let bufferLength = Int(CC_SHA1_BLOCK_BYTES)
var buffer = Array<UInt8>(count: bufferLength, repeatedValue: 0)
var read = 0
repeat {
read = inputStream.read(&buffer, maxLength: bufferLength)
guard read != -1 else {
return nil
}
CC_SHA1_Update(&ctx, buffer, CC_LONG(read))
} while read > 0
guard let data = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH)) else {
return nil
}
CC_SHA1_Final(UnsafeMutablePointer<UInt8>(data.mutableBytes), &ctx)
return data.hex
}
let arguments = Process.arguments.dropFirst()
let fileManager = NSFileManager.defaultManager()
for argument in arguments {
let url = NSURL(fileURLWithPath: argument, isDirectory: false)
guard let path = url.path where fileManager.fileExistsAtPath(path), let hash = sha1(url) else {
print("\(argument) could not be hashed")
continue
}
print("SHA1(\(path))= \(hash)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment