Hash string with SHA512 in Swift

后端 未结 3 1689
天涯浪人
天涯浪人 2021-02-03 11:20

Anyone knows how to reproduce PHP hashing method hash(‘SHA512’, $value, true) in swift ? I tried to use CommonCrypto C library with this code :

extension String          


        
3条回答
  •  面向向阳花
    2021-02-03 12:04

    With CryptoKit added in iOS13, we now have native Swift API:

    import Foundation
    import CryptoKit
    
    // CryptoKit.Digest utils
    extension Digest {
        var bytes: [UInt8] { Array(makeIterator()) }
        var data: Data { Data(bytes) }
    
        var hexStr: String {
            bytes.map { String(format: "%02X", $0) }.joined()
        }
    }
    
    func example() {
        guard let data = "hello world".data(using: .utf8) else { return }
        let digest = SHA512.hash(data: data)
        print(digest.data) // 64 bytes
        print(digest.hexStr) // 309ECC489C12D6EB4CC40F50C902F2B4D0ED77EE511A7C7A9BCD3CA86D4CD86F989DD35BC5FF499670DA34255B45B0CFD830E81F605DCF7DC5542E93AE9CD76F
    }
    

提交回复
热议问题