2017-05-30 82 views
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) 
} 

它顯示的錯誤是這樣的: 參數標籤「(字節長度:, :)」不匹配任何可用的重載我想SHA1 extention添加到字符串中swift3,得到錯誤

+0

不要使用一個CString。直接將字符串編碼爲數據。 – Sulthan

+0

[swift 3 error:Argument labels'(\ _ :)'可能重複不匹配任何可用的重載](https://stackoverflow.com/questions/39443953/swift-3-error-argument-labels-do-不匹配任何可用重載) – Alexander

+0

沒有顯示編碼,它只顯示cstring – shiva

回答

0

解碼類型直接使用Data,請勿使用cString

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

cString是由零字符分隔字符C(CChar)的陣列。你不想那樣。你需要一個原始的字節數組。

然後,你將不得不使用unsafeBytes

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

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

注意digestvardigest的內容將會改變。

您可以在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() 
    } 
} 

那麼你的代碼可以簡化爲:

let digest = value 
    .data(using: .utf8) 
    .sha1() 
    .hexEncodedString()