Search code examples
swiftcryptographypublic-key-encryption

Encrypt Json Payload using public Key (.cer)


Hi I want to encrypt Json Payload using public key that is .cer file. Please suggest how to do this?

  let path = Bundle.main.path(forResource: "Keys123_1", ofType: "cer")
 //get the data asociated to this file
        let urlStt =  URL(fileURLWithPath: path!)
        if let base64String = try? Data(contentsOf: urlStt).base64EncodedString() {
            print(base64String)

        let data2 = Data.init(base64Encoded: base64String)

        let keyDict:[NSObject:NSObject] = [
            kSecAttrKeyType: kSecAttrKeyTypeRSA,
            kSecAttrKeyClass: kSecAttrKeyClassPublic,
            kSecAttrKeySizeInBits: NSNumber(value: 2048),
            kSecReturnPersistentRef: true as NSObject
        ]
            var error:Unmanaged<CFError>? = nil


            guard let key = SecKeyCreateWithData(data2 as! CFData, keyDict as CFDictionary, &error) else {
                print(error)
                return
            }

I am getting this error :

Optional(Swift.Unmanaged<__ObjC.CFError>(_value: Error Domain=NSOSStatusErrorDomain Code=-50 "RSA public key creation from data failed" UserInfo={NSDescription=RSA public key creation from data failed}))

Solution

  • Try this code and encrypt with public key and verify data by decrypt with private key on server side. I followed this link.

    May be this work for you.

    func getPublicKey() -> SecKey? {
    
            let certificateData = try! Data(contentsOf: Bundle.main.url(forResource: "public", withExtension: "cer")!)
    
            let certificate = SecCertificateCreateWithData(nil, certificateData as CFData)
            var trust: SecTrust?
    
            let policy = SecPolicyCreateBasicX509()
            let status = SecTrustCreateWithCertificates(certificate!, policy, &trust)
    
            if status == errSecSuccess {
                let publicKey = SecTrustCopyPublicKey(trust!)!
                return publicKey
            }
            return nil
    }