The following Swift code is crashing on the return statement with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
According to the debugger the result variable has a non-null value. I really want the function to accept Strings and return a String, not NSData. Hoping this is a dumb question and I'm just not seeing it. Been stuck on this for hours!
println(hmac_sha256("sample_data", inKey: "sample_key"))
func hmac_sha256(inData: String, inKey: String) -> (String) {
let data: NSData = inData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let key: NSData = inKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
var result = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key.bytes, size_t(key.length), data.bytes, size_t(data.length), result!.mutableBytes)
return NSString(data: result!, encoding: NSUTF8StringEncoding) as! String
}
Got it. I think I was missing the big picture. The goal was to convert NSData to a hex string. I found a nifty method on github for this here: https://github.com/CryptoCoinSwift/SHA256-Swift/blob/master/SHA256.swift