title: RSA encryption between Swift and C#
body: <p>I need to build the Apple client part to an existing server that is written in .Net/C#. The client should run on OS X and iOS. Part of the communication is done using encrypted data, the C# source being something like</p>
  
  <pre><code>    string privateKey = "xyz…=" // Base64 encoded
      string publicKey  = "abc…=" // Base64 encoded
  
      byte[] decrypt(byte[] encryptedBytes)
      {
          CspParameters cspParams = new CspParameters { ProviderType = 1 /* PROV_RSA_FULL */ };
          RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
          rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
  
          return rsaProvider.Decrypt(encryptedBytes, false);
      }
  </code></pre>
  
  <p>This looks quite simple, but I cannot find a way to implement the <code>encrypt</code> counterpart in Swift.</p>
  
  <p>The <code>publicKey</code> data consists solely of Modulus and Exponent numbers. I can extract the Modulus number from the public key with <code>rsaProvider.ExportParameters(false).Modulus</code>, the Exponent being <code>[1, 0, 1]</code> as usual.</p>
  
  <p>How can I use the Modulus number (or the <code>publicKey</code> string constant itself) in my Swift application on the OS X / iOS client side, and how do I encrypt a plaintext there that can be decrypted on the C# server side?</p>
  
  <p>I understand that Apple is not very fond of introducing cryptographic keys in such a low-level fashion, but there seems to be a possibility to import such a key into the keychain and then use it for encryption.</p>
  
  <p>I have the building blocks (<code>SecItem…()</code>, <code>SecKeyEncrypt()</code>, etc.) but I cannot get it up and running.</p>