title: Swift: RSA Encrypt a string with a specific private key
body: <p>I need to write a method in Swift which uses a particular PRIVATE KEY to encrypt a timestamp using RSA. This is NOT used for authentication (rather it validates the client app to the server), I know that you would normally encrypt with a public key to ensure security.</p>
  
  <p>I have a key:</p>
  
  <blockquote>
    <p>-----BEGIN RSA PRIVATE KEY-----
    MIICXAIBAAKBgQDIg+wteSjhalc1hSHEiUnz9X1pkrObCjaXMHqeSdfFQ/h5Q1Uh<br/>
    ...<br/>
    o7wjoqFNxFnQMAYvkLzQZ7Y2jjfSJkaTVnhzJIZOfQ0=<br/>
    -----END RSA PRIVATE KEY-----<br/></p>
  </blockquote>
  
  <p>And I need to encrypt a string using this particular key. I have written the Android application version of this app, but if I need to re-generate the keys specifically for iOS it's not a problem, but I would need this file for the Android version as well.</p>
  
  <p>I have looked at the following web sites:<br/></p>
  
  <ol>
  <li><p><a href="http://jslim.net/blog/2013/01/05/rsa-encryption-in-ios-and-decrypt-it-using-php/" rel="nofollow noreferrer">http://jslim.net/blog/2013/01/05/rsa-encryption-in-ios-and-decrypt-it-using-php/</a> Seems useful but it insists that the key be in a .der format - plus it's in Objective-C. Is it possible to generate a Key pair in both DER and PEM format, or convert between the two (using something like <a href="https://www.sslshopper.com/ssl-converter.html" rel="nofollow noreferrer">https://www.sslshopper.com/ssl-converter.html</a>)?</p></li>
  <li><p><a href="https://github.com/henrinormak/Heimdall" rel="nofollow noreferrer">https://github.com/henrinormak/Heimdall</a> - but you cannot import a custom private key</p></li>
  <li><p><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> - seems long winded and is also in objective-c</p></li>
  </ol>
  
  <p>One requirement is that all apps use the SAME key - it cannot be generated by each installation of the app. Also my Android app must be able to use the key as well (I am open to rethinking the Android version as leaving the key as a RAW file is not preferred for me).</p>
  
  <p>Any help will be appreciated.<br/>
  <br/>
  Other references checked:<br/>
  <a href="https://stackoverflow.com/questions/4828803/how-to-encrypt-a-string-with-private-key-and-decrypt-with-public-key">How to encrypt a string with private key and decrypt with public key?</a><br/>
  <a href="https://stackoverflow.com/questions/25673005/using-rsa-public-key-to-encrypt-a-string">Using RSA public key to encrypt a string</a><br/></p>