Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt data in javascript and decrypt in php?

Is there any javascript function that can encrypt data: For example i want to use encrypted data in my URL passed by ajax GET request,

http://sample.com/mypage/TDjsavbuydksabjcbhgy

where TDjsavbuydksabjcbhgy an encrypted data equivalent to 12345. Now i want to retrieve that data in PHP by decrypting it, so that i can use the 12345.

Is it possible? or any suggestion on how to do that.

Thanks in advance.

like image 977
Trez Avatar asked Mar 10 '10 02:03

Trez


1 Answers

I found (Bridge between server and client) is the perfect way. the server-side encrypting and decrypting using php is not the matter. but client side and javascript encrypting means no Security because your code, encryption key, alghoritm and all is available for public users. (I found this answer and SSL use as described above). Finally i encrypt both client and serverside with a trick. you can load you random encryption key first of php script and use it in your jquery and so every user have many keys per request which will be usefull for same request. every session encrypted afterwards it's a unusable key. For Maximum Security you can extend this idea (Because of some security purpose I can't describe more but Solved this way.) Example: index.php

 <?php

 $curl = curl_init();
 $url='http://some.xyz/keygen.php';
 ###we set url in a var to insure that anyone can't change it way.
 curl_setopt($curl, CURLOPT_URL, $url);
 curl_setopt($curl, CURLOPT_POST, true);        
 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  $reply=curl_exec($curl);
 //$reply-< session key is generated in another page and replied to this
  //ex :15984762255sadasf4a5sfd5asfda745
 ?>

Client-side(same index.php page)-using forge or cryptojs for encrypting: we echo random generated recieved key for encryption by php in jquery script and do this for all inputs of form.**

<script>
     $('#form').find('input').each(function(){      
    rsa.keypair = keypair;
     var pemPublic = forge.pki.publicKeyToPem(<?php echo($reply); ?>,
   encoded=rsa.keypair.publicKey.encrypt($("#cleartext").val()),
    final = forge.util.encode64(encoded);
   </script>

Send Final by ajax and decrypt server side by php. Don't forget You Keep Private key for decryption in database or any safe place for decryption. Notice : You must do many shortcuts like this to achieve 100% secuirty. Hope To Be Helpful.

like image 57
Behnam Alavi Avatar answered Sep 18 '22 01:09

Behnam Alavi