Reputation:
Let's say I want to get the checksum for bash
located in the /bin
directory of OSX using Swift 2.x. For my version of OSX, the MD5 is
5d7583d80e5314ac844eedc6d68c6cd7
I calculated it using md5 bash
. I also verified it using an online tool.
I decided to use CommonCrypto since it looks like it may have a speed advantage over other options at this time. When I run my code I get a different result:
bash: d574d4bb40c84861791a694a999cce69
Any help would be appreciated. The contents of both the bridging-header and AppDelegate are below.
md5-Bridging-Header.h
#import <CommonCrypto/CommonCrypto.h>
AppDelegate.swift
import Cocoa
extension String {
func md5() -> String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
let hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash as String)
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
let fm = NSFileManager.defaultManager()
let path = "/bin"
let items = try! fm.contentsOfDirectoryAtPath(path)
for item in items {
print("\(item): " + item.md5())
}
}
}
Upvotes: 3
Views: 2186
Reputation: 2070
I think your program calculates the MD5 of the String "bash"
, but not of content of the file named bash.
Upvotes: 2