有没有办法在 Swift 游乐场中使用 Common Crypto? [英] Is there a way to use Common Crypto in a Swift playground?

查看:36
本文介绍了有没有办法在 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: "")
}

这篇关于有没有办法在 Swift 游乐场中使用 Common Crypto?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆