DEV Community

Discussion on: CryptoKit Basics: End-to-End Encryption

Collapse
 
harishios profile image
harishios

Hi,

Great Tutorial. Can I use CryptoKit framework in Objective C?

I tried to import but I couldn't.

Collapse
 
tallinn1960 profile image
Olaf Schlüter

No, you can't just by importing it (what did you try to #import at all as there isn't any .h for CryptoKit?). CryptoKit is Swift-only which may be a writing on the wall to abandon Objective-C for any new project.

What you can do is to write a Swift Wrapper class:

import Foundation
import CryptoKit

@objc class Crypto: NSObject  {    
    @objc static func SHA256hash(data: Data) -> Data {
        let digest = SHA256.hash(data: data)
        return Data(digest);
    }
}
Enter fullscreen mode Exit fullscreen mode

and call it from Objective C by:

NSData *nsdata = [Crypto SHA256hashWithData: input]; // input is of type NSData *
Enter fullscreen mode Exit fullscreen mode

Note, that to make any Swift class and its methods within your project annotated with @objc visible in Objective-C you need to do

#import "<project-name>-Swift.h"
Enter fullscreen mode Exit fullscreen mode

with <project-name> being the name of your Xcode project. That header file is auto-generated by Xcode. You won't see it anywhere but it is there.

It is fortunate that all datatypes used by CryptoKit follow the DataProtocol and are as such convertible to and from Data. You may use the Data/NSData combo as the universal data exchange type. Most important aside from data being processed are public and private keys.