在Swift中将字符串和键转换为SHA256

时间:2018-10-07 16:03:53

标签: swift encryption cryptography

好吧,我尝试了数十种密码学尝试,将答案复制到:

字符串:1538831506GET / v2 /用户

键:R11ScShruvOGBkwMhxCPJEmWLKnwpeLf

预期结果:b4f28c23d9195a3903eeb8aa6214f632f415bbdfbfa2c58f08dad96529bfbdc2

Convert online to SHA256

但是似乎没有任何答案。我已经尝试过CryptoSwift,CommonCrypto(objective-c),IDZSwiftCommonCrypto ..似乎没有任何作用。

以下是一些示例代码:

    func getHMacSHA256(forMessage message: String, key: String) -> String? {


    //CommonCrypto
    let str = message
    let hmac_sha256 = str.hmac(algorithm: .sha256, key: key)
    print(hmac_sha256)
    let hex: String = hmac_sha256.unicodeScalars.filter { $0.isASCII }
        .map { String(format: "%X", $0.value) }
        .joined()
    print(hex)

    //IDZSwiftCommonCrypto
    let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha256, key: key).update(string: message)?.final()


    if let encryptedData = hMacVal {
        let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
        let base64String = decData.base64EncodedString(options: .lineLength64Characters)
        let hexString = (decData as Data).hexEncodedString()
        print("base64String: \(base64String)")
        print("hexString: \(hexString)")
        return hexString
    } else {
        return nil
    }
}

0 个答案:

没有答案