1 Reply
      Latest reply on Oct 5, 2015 1:50 AM by eskimo
      chinmoydas Level 1 Level 1 (0 points)

        In my iOS library, I have a Base64 encoded string containing the X.509 RSA 2048 bit public key. I want to encrypt a string using this public key. Can anyone please provide some Objective C code reference, mentioning the libraries I need to include?

        The equivalent java code looks as below:


        byte[] keyBytes = Base64.decodeBase64(publicKeyData); / X509EncodedKeySpec rsaPublicKeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); encryptedData = cipher.doFinal(dataToEncrypt);

        • Re: Encryption using X.509 2048 bit public key in iOS
          eskimo Apple Staff Apple Staff (13,395 points)

          You can decode the Base64 using -[NSData initWithBase64EncodedString:options:.

          That will give you either an ASN.1 SubjectPublicKeyInfo or an ASN.1 RSAPublicKey structure.  If it’s the former, you will need to strip the SubjectPublicKeyInfo header to get the RSAPublicKey.

          You can add that key to your keychain (using SecItemAdd) and thus get a SecKeyRef.  You can pass that SecKeyEncrypt to do the encryption.

          This isn’t much fun.  If you can change the server side of things, I recommend that you have the server send you a certificate.  Importing a certificate into iOS is trivial (SecCertificateCreateWithData) and getting the public key from that certificate is also pretty easy (create a trust object using SecTrustCreateWithCertificates, evaluate that trust object, then get the public key via SecTrustCopyPublicKey).

          Share and Enjoy

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