我如何通过邮寄请求发送带有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
}
提前致谢!
答案 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在游乐场工作并且我懒得把整个项目都包围在这里,所以我有点畏惧这一点,但是重要的部分在这里。
data.map
迭代哈希中的每个字节String(format: "%02x"...)
joined()