Is there a way to use Common Crypto on a Swift playground?

I play with the REST API on the Xcode playground and I need to do something with SHA1. All the solutions that I found depend on Common Crypto, and it seems that they are not available directly on the Swift playground. Is there any way SHA1 something on the Swift playground?

+3
source share
3 answers

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: "") } 
0
source

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 a MacOS and iOS playground that uses it in the repository.

0
source

Zoul 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 a terminal with Apple Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1) , but see, it works on Ubuntu: Error: using an unauthorized authentication process .

-1
source

Source: https://habr.com/ru/post/987361/


All Articles