简体   繁体   中英

How can I change sha1 in base64 encoding in swift?

I have to convert string to sha1 and then use base64. Simply base64_encode(sha1(My_String)) . I want to do that but I can't fix it correctly. I can convert SHA1 with that code: let firstTry = SHA1.hash(from: "call") but when I try to make it in base64 it gave error which is say string not allowed. How can I convert base64? Thanks for your attention.

I try to conver c[all] to sha1 with that code :

let str = "c[all]"
let den3 = str.sha1()

its working good and return correct which is : 0fee061faab109e27b75010f2f1a0d8258bab7c5

And when I add let den3 = str.sha1().toBase64() I get MGZlZTA2MWZhYWIxMDllMjdiNzUwMTBmMmYxYTBkODI1OGJhYjdjNQ== which is wrong actually I need to get that: D+4GH6qxCeJ7dQEPLxoNgli6t8U=

Where is my issue?

Here my extensions

extension String {
    func sha1() -> String {
        let data = Data(self.utf8)
        var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
        data.withUnsafeBytes {
            _ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &digest)
        }
        let hexBytes = digest.map { String(format: "%02hhx", $0) }
        return hexBytes.joined()
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}

You could use CryptoKit like this

import CryptoKit

let str: String = "Hello, world!"

//Get the SHA1 hash
let hash = Insecure.SHA1.hash(data: str.data(using: .utf8)!)

//Get string representation of the hash (matches hash.description)
let hashedString = hash.map({ String(format: "%02hhx", $0) }).joined()

//Get the base64 string
let encodedString = hashedString.data(using: .utf8)!.base64EncodedString()

On iOS 13+, you can use CryptoKit as follows:

import CryptoKit

extension String {
    func base64EncodedSHA1Hash(using encoding: Encoding = .utf8) -> String? {
        guard let data = data(using: encoding) else { return nil }
        let hash = Data(Insecure.SHA1.hash(data: data))
        return hash.base64EncodedString()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM