0

I want to convert this code from Objective C to Swift 3 :

const char *cKey  = [keyStr cStringUsingEncoding:NSISOLatin1StringEncoding];
const char *cData = [mixStr cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSMutableString *mac = [NSMutableString string];
for (int i=0; i<sizeof cHMAC; i++){
    [mac appendFormat:@"%02hhx", cHMAC[i]];
}  

So i write this but output in Objective C has 64 count and in my Swift code has 44 count.Therefor i think my swift code is wrong:

let cKey = encryptedStrKEYDataString.cString(using: String.Encoding.isoLatin1)
let cData = mix.cString(using: String.Encoding.isoLatin1)
let algorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
let size = Int(CC_SHA256_DIGEST_LENGTH)
var result = [CUnsignedChar](repeating: 0, count: size )
CCHmac(algorithm, cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result)
let hmacData:NSData = NSData(bytes: result, length: size)
let hmacBase64 = hmacData.base64EncodedString(options: [.lineLength64Characters])
reza_khalafi
  • 6,230
  • 7
  • 56
  • 82
  • Please check this @MartinR – reza_khalafi May 06 '17 at 08:07
  • You ObjC code creates a hex-encoded string from the Data, and the Swift code a Base64 encoded string, that is of course different. Have a look at this answer http://stackoverflow.com/a/35620451/1187415 to the duplicate. – Martin R May 06 '17 at 08:10
  • That code does not work on swift 3 ... :| @MartinR – reza_khalafi May 06 '17 at 08:47
  • But it shows how to hex-encode the data. There are also 24 more search results for `[swift] kCCHmacAlgSHA256`. You can also use this: http://stackoverflow.com/a/40089462/1187415. – Martin R May 06 '17 at 08:51
  • For laravel encryption you can use pod 'LaraCrypt' and find mac function in it. swift3 – reza_khalafi May 25 '17 at 05:57

0 Answers0