Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Common crypto code from Objective-C to Swift?

I am working on convert Objective-C Code to Swift. Here we found that CommonCrypto is not available in Swift.

So, we do module.map file and access Common Crypto file using mapping in my exciting Swift project. I have write below code for Objective-C to Swift.

But I am facing issues in code conversion. Below I have written both language code. PLEASE NOTE THAT THIS SWIFT CODE CONTAINS ERRORS. It is not perfect. Please help me to solve Swift language code.

Objective-C Code:

- (NSData *) hashKey:(NSString *)hash{
    unsigned char result[1000];
    const char *cStr = [hash UTF8String];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);

    for (int jval = 0, kval = 16; jval < 8;) {
        result[kval++] = result[jval++];
    }
    return [NSMutableData dataWithBytes:result length:24];;
}

- (NSData *) myEncrypt:(NSString *)encryptData{
    NSData *myKeyData = [self hashKey:MySecretKey];
    NSData *myRawData = [encryptData dataUsingEncoding:NSUTF8StringEncoding];

    size_t buffer_size           = [myRawData length] + kCCBlockSize3DES;
    void* buffer                 = malloc(buffer_size);
    size_t num_bytes_encrypted   = 0;

    uint8_t iv[8] = { 56, 101, 63, 23, 96, 182, 209, 205};

    CCCryptorStatus Crypto_status = CCCrypt(kCCEncrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding,
                                            [myKeyData bytes],
                                            kCCKeySize3DES,
                                            iv,
                                            [myRawData bytes],
                                            [myRawData length],
                                            buffer,
                                            buffer_size,
                                            &num_bytes_encrypted);

    if (Crypto_status == kCCSuccess){
        NSData *myResult = [NSData dataWithBytes:buffer length:num_bytes_encrypted];
        free(buffer);
        return myResult;
    }
    else {
        free(buffer);
        return nil;
    }
}


- (NSData *) myDecrypt:(NSData *)decryptData{

    NSUInteger mydata_len = [decryptData length];
    NSData *keyData = [self hashKey:MySecretKey];

    size_t buffer_size           = mydata_len + kCCBlockSizeAES128;
    void* buffer                 = malloc(buffer_size);
    size_t num_bytes_encrypted   = 0;

    uint8_t iv[8] = { 56, 101, 63, 23, 96, 182, 209, 205};

    CCCryptorStatus decrypt_status = CCCrypt(kCCDecrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding,
                                             [keyData bytes],
                                             kCCKeySize3DES,
                                             iv,
                                             [decryptData bytes],
                                             mydata_len,
                                             buffer,
                                             buffer_size,
                                             &num_bytes_encrypted);

    if (decrypt_status == kCCSuccess){
        NSData *myResult = [NSData dataWithBytes:buffer length:num_bytes_encrypted];
        free(buffer);
        return myResult;
    }
    else {
        free(buffer);
        return nil;
    }

}

Swift Code:

func hashKey(hash:String) -> NSData{

    let digestLength = Int(CC_MD5_DIGEST_LENGTH)
    let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
    var cStr = hash.cStringUsingEncoding(NSUTF8StringEncoding)
    var strLen = CC_LONG(strlen(cStr!))

    CC_MD5(cStr!, strLen, result)

    var kval = 16

    for (var jval=0; kval==16; jval<8){
    result [kval++] = result[jval++] ***//Here We Got An Error: Cannot assign a value of type 'CUnsignedChar' to a value of type '[Int]'***

    }

    return NSMutableData(bytes: result, length: 24)
}


func myEncrypt(encryptData:String) -> NSData?{

    var myKeyData : NSData = self.hashKey(MySecretKey)
    var myRawData : NSData = encryptData.dataUsingEncoding(NSUTF8StringEncoding)!

    var buffer_size : size_t = myRawData.length + kCCBlockSize3DES
    var buffer = UnsafeMutablePointer<NSData>.alloc(buffer_size)
    var num_bytes_encrypted : size_t = 0

    var iv : [UInt8] = [56, 101, 63, 23, 96, 182, 209, 205]

    let operation: CCOperation = UInt32(kCCEncrypt)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
    let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)
    let keyLength        = size_t(kCCKeySize3DES)

    var Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, options, myKeyData.bytes, keyLength, iv, myRawData.bytes, myRawData.length, buffer, buffer_size, &num_bytes_encrypted)

    if UInt32(Crypto_status) == UInt32(kCCSuccess){

    var myResult: NSData = NSData(bytes: buffer, length: num_bytes_encrypted)
    free(buffer)
    return myResult
}else{
    free(buffer)
    return nil
    }

}


func myDecrypt(decryptData : NSData) -> NSData?{

    var mydata_len : Int = decryptData.length
    var keyData : NSData = self.hashKey(MySecretKey)

    var buffer_size : size_t = mydata_len+kCCBlockSizeAES128
    var buffer = UnsafeMutablePointer<NSData>.alloc(buffer_size)
    var num_bytes_encrypted : size_t = 0

    var iv : [UInt8] = [56, 101, 63, 23, 96, 182, 209, 205]

    let operation: CCOperation = UInt32(kCCDecrypt)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
    let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)
    let keyLength        = size_t(kCCKeySize3DES)

    var decrypt_status : CCCryptorStatus = CCCrypt(operation, algoritm, options, keyData.bytes, keyLength, iv, decryptData.bytes, mydata_len, buffer, buffer_size, &num_bytes_encrypted)

    if UInt32(decrypt_status) == UInt32(kCCSuccess){

    var myResult : NSData = NSData(bytes: buffer, length: num_bytes_encrypted)
    free(buffer)
    return myResult
}else{
    free(buffer)
    return nil

    }
}
like image 983
iOS Dev Avatar asked Jun 23 '15 13:06

iOS Dev


Video Answer


2 Answers

for (var jval=0; kval==16; jval<8){
    return [kval++] = result[jval++] ***//Here We Got An Error: Cannot assign a value of type 'CUnsignedChar' to a value of type '[Int]'***
}

As @Francisco notes, this is incorrect. You're trying to return in the middle of the loop. This is an obvious typo. You meant result[kval++] not return [kval++].

But there's another problem. You modified the for loop. It was:

for (int jval = 0, kval = 16; jval < 8;) {

That's basically the same in Swift:

for var jval = 0, kval = 0; jval < 8; {
like image 187
Rob Napier Avatar answered Oct 22 '22 00:10

Rob Napier


Swift 2.0

Add Security.framework

#import <CommonCrypto/CommonCrypto.h> (in bridging header)

Sample md5 method:

func mac_md5(string string: String) -> (NSData?) {
    let data = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
    let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))!
    if (data.length > 0) {
        CC_MD5(data.bytes,
            CC_LONG(data.length),
            UnsafeMutablePointer<UInt8>(result.mutableBytes))
    }
    return result
}

Test:

let dataString = "Here is the data longer"
var mac = mac_md5(string:dataString) as! NSMutableData
print("mac: \(mac)")

Output:

mac: <e3b741ae cadf6725 03e3c95c 9d88a9a6>

The code at the end in the question is copying the first 8 bytes at the end of the first 16 bytes creating a 24 byte 3DES key (aka 2TDEA). This is seen mainly in application achieving DES and 3DES compatibility in the encryption methods.

Sample code:

mac.appendData(mac.subdataWithRange(NSMakeRange(0, 8)))
println("mac: \(mac)")

Output:

mac: <e3b741ae cadf6725 03e3c95c 9d88a9a6 e3b741ae cadf6725>

Sample 3DES method:

func testCrypt3DES(data data:NSData, keyData:NSData, ivData:NSData, operation:CCOperation) -> NSData? {
    let keyBytes = UnsafePointer<UInt8>(keyData.bytes)
    let ivBytes = UnsafePointer<UInt8>(ivData.bytes)
    let dataLength = Int(data.length)
    let dataBytes  = UnsafePointer<UInt8>(data.bytes)
    let cryptData: NSMutableData! = NSMutableData(length: Int(dataLength) + kCCBlockSize3DES)
    let cryptPointer = UnsafeMutablePointer<UInt8>(cryptData.mutableBytes)
    let cryptLength  = size_t(cryptData.length)

    let keyLength              = size_t(kCCKeySize3DES)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
    let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)

    var numBytesEncrypted :size_t = 0

    let cryptStatus = CCCrypt(operation,
        algoritm,
        options,
        keyBytes, keyLength,
        ivBytes,
        dataBytes, dataLength,
        cryptPointer, cryptLength,
        &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.length = Int(numBytesEncrypted)

    } else {
        print("Error: \(cryptStatus)")
    }

    return cryptData;

// Test code:

let keyString = "!Use a data key!"
let keyData = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!

let ivString = "Use a iv"
let ivData = (keyString as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!

let message = "Don´t try to read this text. Top Secret Stuff"
let data = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!

print("data:          \(data)")
if let encryptedData = testCrypt3DES(data:data, keyData:keyData, ivData:ivData, operation:UInt32(kCCEncrypt)) {
    print("encryptedData: \(encryptedData)")
    if let decryptedData = testCrypt3DES(data:encryptedData, keyData:keyData, ivData:ivData, operation:UInt32(kCCDecrypt)) {
        print("decryptedData: \(decryptedData)")
    }
}

Output:

data:          <446f6ec2 b4742074 72792074 6f207265 61642074 68697320 74657874 2e20546f 70205365 63726574 20537475 6666>
encryptedData: <b146c869 df2eec94 fd4656fd 02757e25 718cc32e 35c51907 31866a1c 99f8e2b9 de3ba203 41a49b0f 8fd5dc4c d7721333>
decryptedData: <446f6ec2 b4742074 72792074 6f207265 61642074 68697320 74657874 2e20546f 70205365 63726574 20537475 6666>
like image 33
zaph Avatar answered Oct 22 '22 02:10

zaph