简体   繁体   中英

Ios swift SHA1 encryption

In my android app i have a hashed string that i want to compare with a regular string from an edittext. I do that using the following

try {
         MessageDigest hashDigester = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
return (new BigInteger(1, hashDigester.digest(pin.getBytes())).toString(16)).equals(object.getPin());

The above code works fine. Now i am tring to do the same in ios using swift 3.0 I tried using CryptoSwift to create the hash from the edittext like this

text.sha1()

and i also tried using the below

extension Data {


    func hexString() -> String {
        let string = self.map{String(format:"%02x", Int($0))}.joined()
        return string
    }


    func SHA1() -> Data {
        var result = Data(count: Int(CC_SHA1_DIGEST_LENGTH))
        _ = result.withUnsafeMutableBytes {resultPtr in
            self.withUnsafeBytes {(bytes: UnsafePointer<UInt16>) in
                CC_SHA1(bytes, CC_LONG(count), resultPtr)
            }
        }
        return result
    }

}

extension String {

    func hexString() -> String {
        return self.data(using: .utf8)!.hexString()
    }

    func SHA1() -> String {
        return self.data(using: .utf8)!.SHA1().hexString()
    }

}

Both gave me the same result but not the same with my android code. Do you have any suggestions how should i adjust my swift code?

You can add some small improvements to shorten your code in Swift 4:

extension Data {

    var hexString: String {
        return map { String(format: "%02hhx", $0) }.joined()
    }

    var sha1: Data {
        var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
        self.withUnsafeBytes({
            _ = CC_SHA1($0, CC_LONG(self.count), &digest)
        })
        return Data(bytes: digest)
    }

}

extension String {

    var hexString: String {
        return self.data(using: .utf8)!.hexString
    }

    var sha1: Data {
        return self.data(using: .utf8)!.sha1
    }

}

It was my mistake! The functions where correct i was passing the wrong input

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