1 Reply
      Latest reply on Jun 27, 2018 2:20 AM by eskimo
      flarosa Level 1 Level 1 (0 points)



        I have a base64-encoded string which I am told contains an x.509 public key. I need to extract the key and use it to encode a message.


        Decoding from the string to a Data object yields 294 bytes of data.


        I am not sure what to do next. I tried using SecKeyCreateWithData, which provided a result, but when I attempted to encrypt my message I got an error (OSStatus -50).


        Here is my code:

          let keyDict:[NSObject:NSObject] = [
               kSecAttrKeyType: kSecAttrKeyTypeRSA,
               kSecAttrKeyClass: kSecAttrKeyClassPublic,
               kSecAttrKeySizeInBits: NSNumber(value: 2048),
               kSecReturnPersistentRef: true as NSObject
          let publickeysi = SecKeyCreateWithData(data2! as CFData, keyDict as CFDictionary, nil)
          //Encrypt a string with the public key
          let message = clearStr
          let blockSize = SecKeyGetBlockSize(publickeysi!)
          var messageEncrypted = [UInt8](repeating: 0, count: blockSize)
          var messageEncryptedSize = blockSize
          var status: OSStatus!
          status = SecKeyEncrypt(publickeysi!, SecPadding.PKCS1, message, message.count, &messageEncrypted, &messageEncryptedSize)
          if status != noErr {
               print("Encryption Error!")
        • Re: Decoding an x.509 public key?
          eskimo Apple Staff Apple Staff (10,605 points)

          This is probably the SubjectPublicKeyInfo / RSAPublicKey distinction, which I explained in detail in this thread.

          My general advice on this front is to have your server side wrap the public key in a certificate, which is very easy to import on iOS.  If you can’t do that then you will need to dive into the details.

          Share and Enjoy

          Quinn “The Eskimo!”
          Apple Developer Relations, Developer Technical Support, Core OS/Hardware
          let myEmail = "eskimo" + "1" + "@apple.com"