【问题标题】:Q: Getting a File's MD5 Checksum in Swift问:在 Swift 中获取文件的 MD5 校验和
【发布时间】: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 给你什么? ;)

标签: swift macos swift2


【解决方案1】:

我认为您的程序会计算字符串 "bash" 的 MD5,但不会计算名为 bash 的文件的内容。

【讨论】:

  • 需要更多的咖啡。谢谢!
猜你喜欢
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
相关资源
最近更新 更多