问题
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?
回答1:
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: "")
}
回答2:
There's a CommonCrypto Swift wrapper https://github.com/onmyway133/Arcane
You should be able to import it into your playground as there is an example for both a MacOS and iOS playground using it in the repository.
回答3:
Zoul's solution, ported to 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: "")
}
Note: works on Terminal with Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1), however see, running on Ubuntu: Error: Use of unresolved Identifier 'Process'
来源:https://stackoverflow.com/questions/33032758/is-there-a-way-to-use-common-crypto-in-a-swift-playground