在Swift中获取文件的MD5校验和

3

假设我想使用Swift 2.x获取位于OSX的/bin目录中的bash的校验和。对于我的OSX版本,MD5值为

 5d7583d80e5314ac844eedc6d68c6cd7

我使用md5 bash计算了它。我还使用了一个在线工具进行验证。

我决定使用CommonCrypto,因为它看起来可能比其他选项在速度上有优势。当我运行我的代码时,我得到了不同的结果:

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())
        }
    }

}

4
你尝试过调试你的代码吗?你计算了bin目录中所有文件名的MD5哈希值。"d574d4bb40c84861791a694a999cce69"是字符串"bash"的MD5哈希值。你没有在任何地方读取文件内容。 - Martin R
md5 -s bash 会给你什么结果? ;) - Mike Pollard
1个回答

3
我认为你的程序计算的是字符串 "bash" 的 MD5 值,而不是名为 bash 的文件内容的 MD5 值。

3
需要更多的咖啡。谢谢! - rvg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接