title: Reading PEM public key into iOS
body: <p>I have a base64 public key that was generated by java using this code:</p>
  
  <pre><code>RSAPublicKeySpec rsaKS = new RSAPublicKeySpec(modulus, pubExponent);
  RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(rsaKS);
  byte[] encoded = rsaPubKey.getEncoded();
  String base64 = Base64.encodeToString(encoded, Base64.DEFAULT);
  Log.e(null, "base64: " + base64);
  </code></pre>
  
  <p>This results in a Base64 string.</p>
  
  <p>In OSX I can get a SecKeyRef using this code:</p>
  
  <pre><code>// Create the SecKeyRef using the key data
  CFErrorRef error = NULL;
  CFMutableDictionaryRef parameters = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, NULL);
  CFDictionarySetValue(parameters, kSecAttrKeyType, kSecAttrKeyTypeRSA);
  CFDictionarySetValue(parameters, kSecAttrKeyClass, kSecAttrKeyClassPublic);
  SecKeyRef keyRef = SecKeyCreateFromData(parameters, (__bridge CFDataRef)[pubKey base64DecodedData], &amp;error);
  </code></pre>
  
  <p>However in iOS there is no <code>SecKeyCreateFromData</code> method.</p>
  
  <p>I can use the Base64 string in iOS using <a href="http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/">this code</a> which adds it to the keychain, then retrieves it again as a <code>SecKeyRef</code> however i'd much rather not have to add the cert to the keychain just to be able to retrieve it to use it once.</p>
  
  <p>Doing some research, it seems I should be able to use <code>SecCertificateCreateWithData</code> to create a certificate to use in iOS from the Base64 string I have, however I always get back a NULL cert when using this code:</p>
  
  <pre><code>NSString* pespublicKey = @"MIGfMA0GCSqGSIb3....DCUdz/y4B2sf+q5n+QIDAQAB";
  NSData* certData = [pespublicKey dataUsingEncoding:NSUTF8StringEncoding];
  SecCertificateRef cert;
  if ([certData length]) {
      cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certData);
      if (cert != NULL) {
          CFStringRef certSummary = SecCertificateCopySubjectSummary(cert);
          NSString* summaryString = [[NSString alloc] initWithString:(__bridge NSString*)certSummary];
          NSLog(@"CERT SUMMARY: %@", summaryString);
          CFRelease(certSummary);
      } else {
          NSLog(@" *** ERROR *** trying to create the SSL certificate from data located at %@, but failed", pespublicKey);
      }
  }
  </code></pre>