title: How to encrypt data using server's public key txt file on iOS
body: <p>I'm working on an iOS application with a java server. I need to encrypt some data using RSA. The RSA public key is a txt file. I want to connvert it into a SecKeyRef. The server is developed by the previous guy. I don't have the access to do anything with the server.</p>
  
  <pre><code>NSData *keyBytes = [[NSData alloc] initWithBase64EncodedString:SERVER_PUBLIC_KEY options:0];
  
  SecCertificateRef mycertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) keyBytes);
  SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
  SecTrustRef myTrust;
  
  if (mycertificate != NULL){
  OSStatus status = SecTrustCreateWithCertificates(mycertificate, myPolicy, &amp;myTrust);
  SecTrustResultType trustResult;
  if(status == noErr) {
      status = SecTrustEvaluate(myTrust, &amp;trustResult);
  }
  CFRelease(mycertificate);
  CFRelease(myPolicy);
  CFRelease(myTrust);
  } else {
      NSLog(@"Hell no!");
  }
  return SecTrustCopyPublicKey(myTrust);
  </code></pre>
  
  <p>The problem is SecCertificateRef is always null. The application crashes when I run the code above! </p>