可变数据包装到json中

时间:2017-03-07 15:25:07

标签: swift swift3

我如何通过邮寄请求发送带有sha256的哈希密码?

 func sha256(string: String) -> Data? {
        guard let messageData = string.data(using:String.Encoding.utf8) else { return nil; }
        var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

        _ = digestData.withUnsafeMutableBytes {digestBytes in
            messageData.withUnsafeBytes {messageBytes in
                CC_SHA256(messageBytes, CC_LONG(messageData.count), digestBytes)
            }
        }
        return digestData
    }

这就是我输入密码的方式。

然后每当我尝试将其作为[String: Any]打包到数组中时,它会在JSONSErialization 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation._SwiftNSData)'

中引发异常
 guard let loginURL = URL(string: LOGIN_URL) else {
            print("Error: cannot create URL")
            return
        }

        var loginURLRequest = URLRequest(url: loginURL)
        loginURLRequest.httpMethod = "POST"

        let content: [String: Any] = ["username": username, "passwordHash": password]
        let json: Data

        do {
            json = try JSONSerialization.data(withJSONObject: content, options: [])
            loginURLRequest.httpBody = json
        } catch {
            print("Error: Can not create JSON")
            return
        }

提前致谢!

1 个答案:

答案 0 :(得分:1)

可能想要做的是将哈希值编码为十六进制字符串。鉴于上面定义的sha256函数,以下内容将执行此操作:

let password = sha256(string: "myPassword")
    .map { return String(format: "%02x", $0) }
    .joined()

let content = [ 
    "username": username,
    "passwordHash": password
]

或者,您可以更改sha256函数以返回字符串(并使其成为字符串的扩展名):

func sha256() -> String? {
    guard let messageData = data(using:String.Encoding.utf8) else {
        return nil
    }

    var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes { digestBytes in
        withUnsafeBytes { messageBytes in
            CC_SHA256(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }

    return digestData.map { return String(format: "%02x", $0) }.joined()
}

注意:由于CommonCrypto在游乐场工作并且我懒得把整个项目都包围在这里,所以我有点畏惧这一点,但是重要的部分在这里。

  1. 使用data.map迭代哈希中的每个字节
  2. 使用String(format: "%02x"...)
  3. 将其转换为十六进制字符串
  4. 将所有内容与joined()
  5. 放在一起