0
func stringSha1(_ value: String) -> String {
    let cstr = value.cString(using: String.Encoding.utf8)
    let data = Data(bytes: cstr, length: (value.characters.count ?? 0))
    let digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
    // This is an iOS5-specific method.
    // It takes in the data, how much data, and then output format, which in this case is an int array.
    CC_SHA1(data.bytes, (data.count as? uint), digest)
    //NSLog(@"SHA1 Digest: %s",digest);
    return stringHexEncode(digest, withLength: CC_SHA1_DIGEST_LENGTH)
}

it shows error like this: Argument labels '(bytes:, length:)' do not match any available overloads

shiva
  • 1
  • 1
  • Dont use a cString. Encode String to Data directly. – Sulthan May 30 '17 at 05:04
  • Possible duplicate of [swift 3 error : Argument labels '(\_:)' do not match any available overloads](https://stackoverflow.com/questions/39443953/swift-3-error-argument-labels-do-not-match-any-available-overloads) – Alexander May 30 '17 at 05:05
  • There is not showing encoding ,it shows only cstring – shiva May 30 '17 at 05:15

1 Answers1

0

Decode to Data directly, don't use cString.

let data = value.data(using: .utf8)

cString is an array of C characters (CChar) delimited by a zero character. You don't want that. You need a raw array of of bytes.

Then you will have to use unsafeBytes:

var digest = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))

data.withUnsafeBytes {
    _ = CC_SHA1($0, CC_LONG(self.count), &digest)
}

Note that digest is a var. The contents of digest will change.

You can create the following extension on Data:

extension Data {
    func 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)
    }

    func hexEncodedString() -> String {
        return self.map { String(format: "%02hhx", $0) }.joined()
    }
}

Then your code can be simplified to:

let digest = value
     .data(using: .utf8)
     .sha1()
     .hexEncodedString()
Sulthan
  • 128,090
  • 22
  • 218
  • 270