有没有办法在 Swift 游乐场中使用 Common Crypto?
问题描述:
我正在 Xcode 游乐场中玩弄 REST API,我需要用 SHA1 散列一些东西.我找到的所有解决方案都依赖于 Common Crypto,而这似乎不能直接在 Swift Playground 中使用.有没有办法在 Swift 游乐场中 SHA1 一些东西?
I am toying with a REST API in an Xcode playground and I need to hash something with SHA1. All the solutions I have found depend on Common Crypto, and that doesn’t seem to be directly available in a Swift playground. Is there a way to SHA1 something in a Swift playground?
答
快速而肮脏的解决方案:
A quick and dirty solution:
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: "")
}