title: OpenSSL RSA Public Key encryption in Java in Server and decryption with Private Key in Client in OSX
body: <p>I have an application which is client/server based. The client is developed for both iOS and OSX. The server is common for both the clients (and server's implementation cannot be changed).</p>
  
  <p>The client developed in iOS generates an RSA public/private key pair and send the public key in base64 encoding to the server. The server (implemented in Java) encrypts some secure data and sends the same to the client who is required to decrypt data with the private key. The RSA key pair is generated on iOS using the Crypto Exercise Sample provided by apple. </p>
  
  <p>The public and private key generated (of key length 1024) in base64Encoding is of length 216 and 844 bytes respectively and of the form provided below.</p>
  
  <pre><code>Private Key:
  MIMAAnQwDQYJKoZIhvcNAQEBBQAkabeCYAAwggJbAgEAAoGBANDV3P+17zCIw/ZIwjM/5q7DeEEi4AVYE2STPnbuApvc0JjC3gx+F+mLtCfR+lxi0TAWqdFK6MkjGzyKONcEHRWxA/7ltFC1RlgEWzxmdr4kOEL5DV6DRep4Ykh4guvGf3A4N1A87com0rSjOoWR++N9HCmGxrnEhgV7gb9wknoRAgMBAAECgYAS+pyvEJXAT22fwFUF21TXpSQUp1q8oZiBl3Ah1ted2p+Kgoszj3IU44Fn7QlXxBNGz4h3YNtvDCWS3JVp1RHfZRonPdrvcwSMSk6M7crxS0NTxZlhvbgTuD2AlKjAT381gMUAxGGm9tvHlxwxhuIFEmXV1rz3hxbPYyFppCCrwQJBAd83wa9FwfGkcWU/gN3I0kJc8EfQwYDooY/V6hLcCYNW7wXyn3ja6Xl9XtgQnPeYSx+h2bGs339cDPKYtG2imm0CQG+PiLA8IHmIJDiEeB+jIRXAizd2aMgsvUomjWmMiYl/SPocvL3HxgGhvNNs8tUJKcw+/JhKPSBFX2+aRF55l7UCQQEZmVsQUs6P35De7T0dlrevVYvAt7QtuwXNTueYo4JXkosslJEPZJxTzs8f6ktC11Q1x1b0KGDBJ2dYW1GTJzzVAkBB6iq3Bi+h3wCXrB1VhAsOUR9we7PZYiXNZA31qSWyadRygvw5nYmueSOaQCi1Ep7xoN2aFXMcWCDVTe7La0hpAkBjBU9PDamhULFstd4hlx2UkPOGGnWZCAnr2zU+r2Q12eK20tjDZzS4TQWZWmKXkI2QAd+SJ44oI6+hZq5AHHEl
  
  Public Key:
  
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADkIJlKBgQDQ1dz/te8wiMP2SMIzP+auw3hBIuAFWBNkkz527gKb3NCYwt4Mfhfpi7Qn0fpcYtEwFqnRSujJIxmTFzjXBB0VsQP+5bRQtUZYBFs8Zna+JDhC+Q1eg0XqeGJIeILrxn9wODdQPO3KJtK0ozqFkfvjfRwphsa5xIYFe4G/cJJ6EQIDAQAB
  </code></pre>
  
  <p>Things are working fine in the iOS world.</p>
  
  <p>I am trying to implement this in the MAC using Objective-c and find that the Crypto Exercise sample is not working as expected. The SecItemCopyMatching is returning failure.</p>
  
  <p>While investigating for the solution found that the public/private key using Open SSL met the criteria of private and public key except for the header and footer that is appended to the generated key pair.</p>
  
  <p>I used the SSCrypto OpenSSL wrapper (<a href="http://septicus.com/products/opensource/" rel="nofollow">http://septicus.com/products/opensource/</a>) to generate the public and private key pair using OpenSSL which is of the form.</p>
  
  <pre><code>-----BEGIN RSA PRIVATE KEY-----
  MIICXQIBAAKBgQCrEgoLjG34pNLj4ahpWlvXZZEhzimg/mJoKJLdrjE3Fg817Qf2
  +iXTPMWAtmCkYgHn9Y99VJSdJzrb0/E1JnxMPva52ZMS8ilS/hSZnXRAlq2OPFMj
  64SU9XDu/eWqJMULELNkBcTtPgTCAkjrDU6Qt2AbwNUwrgufJC8WJEhWdQIDAQAB
  AoGBAKc2Y8E0C44dtdFvEgmge+MH8RuFA6XM4O2Es0Gh8ZMxqb6BKObdTbmzTi3o
  loA3GDveB9puoTEXVm3nNX9JVfYr952+54vEfFGDnUfnsjpzQih5NkODKKxS0NXW
  DsCgemo9QmOYlGUm/mcvdv2gnjrl/E1TgRbC5cJ8bX5O3sAhAkEA04mFvAx+B+mx
  uVH8RxBkv0iB7lEuR87jrZuL7n7LnyHdnstK85xs9mmx95nMhmh6jWD1VIRVbx3X
  XsRqoRVQjQJBAM8HER8bae89Vw6ptBezB3ihs4NZ/dF5jM3ksLN10hm9n00hSSmo
  FaT7PcSizFkoUs2kGcytZuzTkSYVaeM154kCQQC6AXQJ7cYoeRJgjTnS1xRvqnct
  sk6Kr949usepl+6+Z83zInkuiv65Eil+OcvA6D/S703p2k8xXMETQI0uRYrFAkBV
  sIEftQMV6Pe9s/Q80vdGsPdSaM8sAvmKxxt0TFIYIWpsTFiyC0ZaMTuRxih6xrvv
  LfsXwrYVVESB1N8tEkSxAkAbPNx57ceCLMvkknDWuNdygtBgtAskSccktWnbXk9C
  CnpHn/toehb9Grk6pbR1PqLRgD2l8ctiYBq/+2t+L/lp
  -----END RSA PRIVATE KEY-----
  
  -----BEGIN PUBLIC KEY-----
  MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrEgoLjG34pNLj4ahpWlvXZZEh
  zimg/mJoKJLdrjE3Fg817Qf2+iXTPMWAtmCkYgHn9Y99VJSdJzrb0/E1JnxMPva5
  2ZMS8ilS/hSZnXRAlq2OPFMj64SU9XDu/eWqJMULELNkBcTtPgTCAkjrDU6Qt2Ab
  wNUwrgufJC8WJEhWdQIDAQAB
  -----END PUBLIC KEY-----
  </code></pre>
  
  <p>To extract the public key, I stripped of the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" footer and white spaces to extract the public key to be sent to the server. </p>
  
  <p>The problem is that when I strip the header and footer the sent the public key to the server, though the server successfully encrypts the data (using the public key) and sent encrypted data to the client, the decryption using private key (in PEM format) using OpenSSL fails. 
  I think the decryption has failed as when i modify the public key's content (by stripping of the header/fooders), the public and private key seize to be key pairs.</p>
  
  <p>Can somebody help me with the solution such that I am able to use the private key to decrypt the received encrypted data.</p>
  
  <p>Alternatively, can somebody help me in generation of public key/private key pair of abovementioned lengths using objective-c api's (pair as generated by OpenSSL) which will fix the issue I am facing?</p>
  
  <p>Thanks &amp; Regards. </p>
  
  <p>The data encrypted by server using Public Key is an AES key. The size of the AES key after encryption using public key is 176 characters. Here is the code snippet which does it.</p>
  
  <pre><code>public static String encryptAESKey(byte[] aesKeyBytes, String publicKeyStr) {
      String cipherStr = null; 
  
      try {
          PublicKey pkey = getPublicKey(publicKeyStr);
  
          final Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
          cipher.init(Cipher.ENCRYPT_MODE, pkey);
  
          byte[] cipherBytes = cipher.doFinal(aesKeyBytes);
  
          cipherStr = Base64.encodeBase64String(cipherBytes);
  
      } catch (Exception e) {
          e.printStackTrace();
      }
      return cipherStr;
  }
  
  private static PublicKey getPublicKey(String publicKey) throws InvalidKeySpecException, NoSuchAlgorithmException {
  
      KeyFactory rsaKeyFac = KeyFactory.getInstance(RSA_ALGORITHM);
      byte[] keyBytes = Base64.decodeBase64(publicKey.getBytes());
  
      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
      RSAPublicKey rsaPubKey = (RSAPublicKey)rsaKeyFac.generatePublic(keySpec);
      return rsaPubKey;       
  }
  </code></pre>