title: Javascript + PHP Encryption with pidCrypt
body: <p>I have been working on trying to implement an encryption mechanism for passing secure information on my website.  My host charges extra for SSL, and I am not ready for the extra monetary commitment.</p>
  
  <p>I tried to use <a href="https://sourceforge.net/projects/pidcrypt/" rel="nofollow">pidCrypt</a> to encrypt the values on the client side via javascript.  Then, I have tried several techniques for unencrypting on the PHP side.  For some reason, the data just gets garbled.</p>
  
  <p>Can someone point out what I am doing wrong?  Or, should I use a different javascript library for the encryption?  Any advice?</p>
  
  <p>Here's the javascript code that pulls the text to encrypt from an input on the page and the public key from a hidden text area on the page.</p>
  
  <pre><code>$(document).ready(function() {
    $('button').click(function() {
      var dataToSend = new Object();
  
      var input = $('input[name=textToEncrypt]').val();
      var public_key = $('textarea[name=publicKey]').val();
      var params = certParser(public_key);
          var key = pidCryptUtil.decodeBase64(params.b64);
      //new RSA instance
      var rsa = new pidCrypt.RSA();
      //RSA encryption
      //ASN1 parsing
      var asn = pidCrypt.ASN1.decode(pidCryptUtil.toByteArray(key));
      var tree = asn.toHexTree();
      //setting the public key for encryption
      rsa.setPublicKeyFromASN(tree);
      var t = new Date();  // timer
      crypted = rsa.encrypt(input);
      dataToSend.unencrypted = input;
      dataToSend.textToDecrypt = pidCryptUtil.fragment(pidCryptUtil.encodeBase64(pidCryptUtil.convertFromHex(crypted)),64);
      $('body').append(dataToSend.textToDecrypt);
  
  
      $.getJSON('engine.php', dataToSend, function(data) {
        var items = [];
  
        $.each(data, function(key, val) {
           items.push('&lt;li id="' + key + '"&gt;' + key + ': ' + val + '&lt;/li&gt;');
        });
  
        $('&lt;ul/&gt;', {
          'class': 'my-new-list',
          html: items.join('')
        }).appendTo('body');
      });
  
  
    });
  });
  </code></pre>
  
  <p>This is my engine.php code that is supposed to decrypt the value.  Notice that I have tried several different ways from different examples.</p>
  
  <pre><code>&lt;?php
     require_once 'private/keys.php';
  
  
  
  function EncryptData($source)
  {
    /*
     * NOTE:  Here you use the $pub_key value (converted, I guess)
     */
    $key = $DEkeys-&gt;pubKey;
    openssl_public_encrypt($source,$crypttext,$key);
    return(base64_encode($crypttext));
  }
  
  function DecryptData($source)
  {
    /*
     * NOTE:  Here you use the returned resource value
     */
    $decoded_source = base64_decode($source);
    openssl_private_decrypt($decoded_source,$newsource,$DEkeys-&gt;privKey);
    return($newsource);
  }
  
  function EncryptData2($source)
  {
    $fp=fopen("/pathtokey/public.pem","r");
    $pub_key=fread($fp,8192);
    fclose($fp);
    openssl_get_publickey($pub_key);
    /*
     * NOTE:  Here you use the $pub_key value (converted, I guess)
     */
    openssl_public_encrypt($source,$crypttext,$pub_key);
    return(base64_encode($crypttext));
  }
  
  function DecryptData2($source)
  {
    #print("number : $number");
    $fp=fopen("/pathtokey/private.pem","r");
    $priv_key=fread($fp,8192);
    fclose($fp);
    // $passphrase is required if your key is encoded (suggested)
    $res = openssl_get_privatekey($priv_key);
    /*
     * NOTE:  Here you use the returned resource value
     */
    $decoded_source = base64_decode($source);
    openssl_private_decrypt($decoded_source,$newsource,$res);
    return($newsource);
  }
  
  $out = new stdClass;
  
  $out-&gt;hello = 'hello, world!';
  
  if(!empty($_GET["textToDecrypt"])) {
     $out-&gt;raw = $_GET['textToDecrypt'];
     $out-&gt;unencrypted = $_GET['unencrypted'];
       if($DEkeys-&gt;privKey == false) {
         $out-&gt;error = 'Could not read private key';
       }
       $out-&gt;success = openssl_private_decrypt(base64_decode($out-&gt;raw), $decrypted, $DEkeys-&gt;privKey);
       $out-&gt;decrypted = $decrypted;
       $out-&gt;dec2 = DecryptData2($out-&gt;raw);
       $out-&gt;test1 = EncryptData2('testing');
       $out-&gt;test2 = DecryptData2($out-&gt;test1);
  } else {
     $out-&gt;nondata = $_GET['textToDecrypt'];
  }
  
  
  echo json_encode($out);
  </code></pre>
  
  <p>When I enter "test" for the value to decrypt, the PHP shows:
   - decrypted: dGVzdA== 
   - dec2: dGVzdA==</p>
  
  <p>So, neither the openssl_private_decrypt() nor the DecryptData2() functions will correctly decrypt the values.  The EncryptData2() and DecryptData2() will work together though.</p>
  
  <p>Is it possible I am missing something small?  Any advice?</p>
  
  <p>Edit: Here are the commands I used to create the keys --</p>
  
  <p>This creates the private key:</p>
  
  <pre><code> openssl genrsa -out private.pem 1024
  </code></pre>
  
  <p>This creates the public key:</p>
  
  <pre><code> openssl rsa -in private.pem -pubout &gt; public.pem
  </code></pre>