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?

1 answer

  • answered 2017-06-17 18:33 appLogic

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