【问题标题】:Get hash from file using CryptoSwift使用 CryptoSwift 从文件中获取哈希
【发布时间】:2018-03-05 20:29:41
【问题描述】:

所以我尝试从文件中获取哈希值。使用CryptoSwift 库。 truth 是我从 VLC 网站获得的带有哈希值的变量,所以这应该是真的。但是,我生成的散列与我知道的真实散列不同。

我错过了哪一步?

代码:

let filePath = "/Users/pjc/Desktop/vlc-3.0.0.dmg"

let fileURL = URL(fileURLWithPath: filePath)
let truth = "e6f7179cb06809b6101803da3ac4191edb72ecf82f31b8ae7dbf010e1a78ba26"

do {
   let fileData = try Data.init(contentsOf: fileURL)
   print(fileData)
   let fileBytes = fileData.bytes
   let hash = fileBytes.sha256()
   print(hash.debugDescription)

} catch {

   //handle error
   print(error)
}

print(hash)
print(truth)

日志:

fileData: 46818658 bytes
hash.debugDescription: [230, 247, 23, 156, 176, 104, 9, 182, 16, 24, 3, 218, 58, 196, 25, 30, 219, 114, 236, 248, 47, 49, 184, 174, 125, 191, 1, 14, 26, 120, 186, 38]
hash: 105553117580736
truth: e6f7179cb06809b6101803da3ac4191edb72ecf82f31b8ae7dbf010e1a78ba26

【问题讨论】:

  • 提示:230 = 0xE6, 247 = 0xF7, 23 = 0x17, ...
  • 我不熟悉 CryptoSwift 库,但快速浏览一下 README,.toHexString() 可能已经是你要找的了。
  • @MartinR .toHexString() 确实可以解决问题。如果你把它作为一个答案,我会接受它。非常感谢!
  • 我已经回答了你的直接问题,但你可能会从比我更了解加密的人那里看到这个答案:stackoverflow.com/a/34474304/1187415,并改用 Apple 的 CommonCrypto。
  • 最好避免使用 CryptoSwift,除此之外,它比基于 Common Crypto 的实现慢 500 到 1000 倍。 Apple 的 Common Crypto 已通过 FIPS 认证,因此经过了严格的审查,使用 CryptoSwift 在正确性和安全性(例如定时和功率攻击)方面是有机会的。

标签: swift hash cryptoswift


【解决方案1】:
[230, 247, 23, 156, 176, 104, 9, 182, 16, 24, 3, 218, 58, 196, 25, 30, 219, 114, 236, 248, 47, 49, 184, 174, 125, 191, 1, 14, 26, 120, 186, 38]

e6f7179cb06809b6101803da3ac4191edb72ecf82f31b8ae7dbf010e1a78ba26

只是相同哈希值的两种不同表示:第一种 作为整数数组,第二个作为十六进制字符串 字节的表示。

CryptoSwift 库的.toHexString() 方法创建一个 数组中的十六进制字符串,因此

print(hash.toHexString())

应该会产生预期的结果。

【讨论】:

    【解决方案2】:

    计算哈希不需要框架。你可以用 CommonCrypto 做任何事情。您只需要添加一个包含

    的桥接头
    #import <CommonCrypto/CommonCrypto.h>
    

    您可以查看here如何添加桥接头。

    extension Data {
    
        var hexString: String {
            return map { String(format: "%02hhx", $0) }.joined()
        }
    
        var sha256: Data {
            var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
            self.withUnsafeBytes({
                _ = CC_SHA256($0, CC_LONG(self.count), &digest)
            })
            return Data(bytes: digest)
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-20
      • 2010-12-19
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 2016-01-09
      • 1970-01-01
      • 2016-07-22
      • 2013-05-01
      相关资源
      最近更新 更多