title: 256 byte long RSA encryption of AES key
body: <p>I am trying to RSA encrypt the AES key of 32 chars length.
  Finally managed to do so with the help of the pre-generated public key and this RSA implementation for objective-C:
  <a href="https://github.com/ideawu/Objective-C-RSA/blob/master/RSA.m" rel="nofollow noreferrer">https://github.com/ideawu/Objective-C-RSA/blob/master/RSA.m</a></p>
  
  <pre><code>NSData *enc = [RSA encryptData:data publicKey:pubkey];
  </code></pre>
  
  <p>Which then calls the library's methods. Basically, what it does is the following: it creates a SecKeyRef from public key, then it calculates the block_size, data_size etc. And finally it calls the </p>
  
  <pre><code>SecKeyEncrypt(keyRef, kSecPaddingPKCS1, srcbuf + idx, data_len, outbuf, &amp;outlen);
  </code></pre>
  
  <p>I don't really understand what is going inside the encryption methods, but the outcome is the correctly created encrypted key.</p>
  
  <p>Then I am able to decrypt it with a public key with the help of</p>
  
  <pre><code>SecKeyDecrypt(keyRef, kSecPaddingNone, srcbuf + idx, data_len, outbuf, &amp;outlen);
  </code></pre>
  
  <p>The result is absolutely correct.</p>
  
  <p>But the encoded key is 144 bytes long. It is not what I need. For some reason I need the key to be exactly 256 bytes.</p>
  
  <p>My first thought was to fill the rest bytes with some constant variable (e.g. 0), but I thought it is not how it should be done.</p>
  
  <p>The next thought was to use different padding. The name kSecPaddingPKCS1SHA256 sounded like the correct padding, but encoding the key with it instead of the kSecPaddingPKCS1 caused the app to fail with the error:</p>
  
  <pre><code>SecKeyEncrypt fail. Error Code: -50
  </code></pre>
  
  <p>I suppose it has something to do with the block_size, but I have little understanding of the insides of the encryption.</p>
  
  <p>I need the encoded key to be exactly 256 bytes long, how can I do that?</p>