title: Java to PHP - function for X509EncodedKeySpec
body: <p>I have Java sample code for RSA encryption using public key which is in base64 format. Now I want to convert same thing in PHP. I tried to convert but some class are confusing me.This is java sample code.              </p>
  
  <pre><code>public static String encrypt(String msg, String fileName) throws Exception {
      try {
          Cipher cipher = Cipher.getInstance("RSA");
          RSAPublicKey cryptPublicKey = readPublicKeyFromFile(fileName);
          System.out.println("public "+cryptPublicKey);
          cipher.init(1, cryptPublicKey);
          String tempStr = msg;
          int modulus = tempStr.length() / 8;
          if (modulus != 0) {
              for (int i = modulus; i &lt; 8; i++)
                  tempStr = tempStr + " ";
          }
          byte plainData[] = tempStr.getBytes();
          byte binaryCryptData[] = cipher.doFinal(plainData);
          BASE64Encoder encoder = new BASE64Encoder();
          String encData = encoder.encode(binaryCryptData);
          msg = encData;
      } catch (Exception e) {
          e.printStackTrace();
          throw e;
      }
      return msg;
  }
  
  private static RSAPublicKey readPublicKeyFromFile(String fileName) throws Exception {
      RSAPublicKey cryptPublicKey = null;
      try {
          KeyFactory keyFac = KeyFactory.getInstance("RSA");
          FileInputStream fis = new FileInputStream(fileName);
          byte cryptKey[] = new byte[fis.available()];
          fis.read(cryptKey);
          fis.close();
          cryptKey = (new BASE64Decoder()).decodeBuffer(new String(cryptKey));
          X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(cryptKey);
          cryptPublicKey = (RSAPublicKey) keyFac.translateKey(keyFac.generatePublic(encodedKeySpec));
      } catch (Exception e) {
          e.printStackTrace();
          throw e;
      }
      return cryptPublicKey;
  }
  </code></pre>
  
  <p>Now this is what I have tried to achieve samething in PHP:</p>
  
  <pre><code>$keyData =base64_decode(file_get_contents($configValues['metPubKey']));
  
  print_r($keyData);
  $rsa = new Crypt_RSA();
  
  try{
      $rsa-&gt;loadKey($keyData); // public key
      $encryptedToken = base64_encode($rsa-&gt;encrypt($token));
  }catch(Exception $e){
      die;
  }
  </code></pre>
  
  <p>In Java code there is <code>X509EncodedKeySpec</code> class in <code>readPublicKeyFromFile</code> function, which returns public key.I'm not sure what should I use in PHP. And also looks like php script not matching with Java code. Any help on this?</p>