【发布时间】:2016-02-23 16:29:19
【问题描述】:
假设我想使用 Swift 2.x 获取位于 OSX 的 /bin 目录中的 bash 的校验和。对于我的 OSX 版本,MD5 是
5d7583d80e5314ac844eedc6d68c6cd7
我使用md5 bash 计算得出。我还使用online tool 对其进行了验证。
我决定使用 CommonCrypto,因为它看起来可能比 other options at this time 具有速度优势。当我运行我的代码时,我得到了不同的结果:
bash: d574d4bb40c84861791a694a999cce69
任何帮助将不胜感激。 bridging-header 和 AppDelegate 的内容如下。
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())
}
}
}
【问题讨论】:
-
您是否尝试过调试您的代码?您计算 bin 目录中 文件名 的 MD5 哈希值。 “d574d4bb40c84861791a694a999cce69”是字符串“bash”的 MD5 哈希值。您无处可读取文件内容。
-
md5 -s bash给你什么? ;)