title: RSA encryption using SecKeyEncrypt gives error -4 (errSecUnimplemented)
body: <p>I'm trying to encrypt some data with RSA using the Security framework on iOS. I want to encrypt a simple base64-encoded string as follows:</p>
  
  <pre><code>NSData *data = [[NSData alloc] initWithBase64EncodedString:@"aGFsbG8=" options:0x0];
  NSData *encrypted = [pair encrypt:data];
  </code></pre>
  
  <p>The <code>pair</code> variable holds references to a private key and a public key that were succesfully generated before using <code>SecKeyGeneratePair</code>.</p>
  
  <p>The encrypt function looks like this: </p>
  
  <pre><code>- (NSData *)encrypt:(NSData *)data {
      void *buffer = malloc([self blockSize] * sizeof(uint8_t));
      memset(buffer, 0x0, [self blockSize]);
      size_t ciphertextBufferLength = [data length];
      OSStatus res = SecKeyEncrypt([self keyRef], 0x1, [data bytes], [data length], &amp;buffer[0], &amp;ciphertextBufferLength);
      NSLog(@"Result of encryption: %d", res);
      return [NSData dataWithBytesNoCopy:buffer length:[self blockSize] freeWhenDone:YES];
  }
  </code></pre>
  
  <p>The implementation of <code>[self blockSize]</code> is rather straightforward:</p>
  
  <pre><code>- (unsigned long)blockSize {
      return SecKeyGetBlockSize(keyRef);
  }
  </code></pre>
  
  <p>I generate my keys with the following function:</p>
  
  <pre><code>- (BOOL)generateNewKeyPairOfSize:(unsigned int)keySize
  {
      SecKeyRef privKey = [[self publicKey] keyRef];
      SecKeyRef pubKey = [[self publicKey] keyRef];
  
      NSDictionary *privateKeyDict = @{ (__bridge id)kSecAttrIsPermanent : @(YES), (__bridge id)kSecAttrApplicationTag : [[self privateKey] tag] };
      NSDictionary *publicKeyDict = @{ (__bridge id)kSecAttrIsPermanent : @(YES), (__bridge id)kSecAttrApplicationTag : [[self publicKey] tag] };
      NSDictionary *keyDict = @{ (__bridge id)kSecAttrKeyType : (__bridge id)kSecAttrKeyTypeRSA, (__bridge id)kSecAttrKeySizeInBits : @(keySize), (__bridge id)kSecPublicKeyAttrs : publicKeyDict, (__bridge id)kSecPrivateKeyAttrs : privateKeyDict };
      OSStatus res = SecKeyGeneratePair((__bridge CFDictionaryRef)keyDict, &amp;privKey, &amp;pubKey);
      NSLog(@"Result of generating keys: %d", res);
  
      [[self publicKey] setKeyRef:pubKey];
      [[self privateKey] setKeyRef:privKey];
  
      return YES;
  }
  </code></pre>
  
  <p>The problem is that the value of <code>res</code> is <code>-4</code>, meaning <code>errSecUnimplemented</code> according to the documentation. I'm not sure what I'm doing wrong here since I have all parameters required. I'm not sure whether there is a mistake in the parameters and where. The call the <code>[self blockSize]</code> return 128.</p>
  
  <p>Can anyone help me with this?</p>