有没有办法在Swift游乐场中使用Common Crypto?

时间:2015-10-09 07:48:23

标签: swift-playground commoncrypto

我正在玩Xcode游戏机中的REST API,我需要使用SHA1哈希。我找到的所有解决方案都依赖于Common Crypto,而且似乎并没有直接在Swift游乐场中提供。有没有办法在Swift游乐场中使用SHA1?

3 个答案:

答案 0 :(得分:0)

快速而肮脏的解决方案:

func SHA1HashString(string: String) -> String {
    let task = NSTask()
    task.launchPath = "/usr/bin/shasum"
    task.arguments = []

    let inputPipe = NSPipe()
    inputPipe.fileHandleForWriting.writeData(string.dataUsingEncoding(NSUTF8StringEncoding)!)
    inputPipe.fileHandleForWriting.closeFile()

    let outputPipe = NSPipe()
    task.standardOutput = outputPipe
    task.standardInput = inputPipe
    task.launch()

    let data = outputPipe.fileHandleForReading.readDataToEndOfFile()
    let hash = String(data: data, encoding: NSUTF8StringEncoding)!
    return hash.stringByReplacingOccurrencesOfString("  -\n", withString: "")
}

答案 1 :(得分:0)

有一个CommonCrypto Swift包装器https://github.com/onmyway133/Arcane

你应该能够将它导入你的游乐场,因为有一个MacOS和iOS游乐场的例子在存储库中使用它。

答案 2 :(得分:-1)

Zoul的解决方案,移植到 Swift 3

import Foundation 

func SHA1HashString(string: String) -> String {
let task = Process()
task.launchPath = "/usr/bin/shasum"
task.arguments = []

let inputPipe = Pipe()
inputPipe.fileHandleForWriting.write(string.data(using:String.Encoding.utf8)!)
inputPipe.fileHandleForWriting.closeFile()

let outputPipe = Pipe()
task.standardOutput = outputPipe
task.standardInput = inputPipe
task.launch()

let data = outputPipe.fileHandleForReading.readDataToEndOfFile()
let hash = String(data: data, encoding: String.Encoding.utf8)!
return hash.replacingOccurrences(of: "  -\n ", with: "")
}

注意:适用于Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1)的终端,但请参阅在Ubuntu上运行:Error: Use of unresolved Identifier 'Process'