3

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?

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
zoul
  • 102,279
  • 44
  • 260
  • 354

3 Answers3

0

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: "")
}
zoul
  • 102,279
  • 44
  • 260
  • 354
0

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.

carlossless
  • 1,171
  • 8
  • 23
  • 1
    In the end I made myself a Swift wrapper, too: https://github.com/zoul/CommonCrypto. – zoul Mar 08 '17 at 17:19
-1

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'

Community
  • 1
  • 1
Kheldar
  • 5,361
  • 3
  • 34
  • 63
  • my playground doesn't seem to find `Process()` ... any idea why? – Buju Mar 22 '17 at 17:11
  • @buju Process is a sys call. That's why I added this works on Terminal and linked the Ubuntu question. – Kheldar Mar 23 '17 at 15:51
  • @buju change the type of playground your using to MacOS in the Utilities pane, it will recognize Process after. – bainfu Jun 03 '17 at 00:14