DEV Community

Cover image for Encrypt string in Js and decrypt in Laravel PHP
Vepa Mirzayev
Vepa Mirzayev

Posted on

Encrypt string in Js and decrypt in Laravel PHP

I am going to show you encrypting data in javascript with JSEncrypt library with use RSA keys and decrypting string in Laravel.It is also supported for UTF8 encoding.

Add the this script url your project in html side

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/3.0.0/jsencrypt.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Basic initialization in JS

      let publicKey= '-----BEGIN PUBLIC KEY----- **** -----END PUBLIC KEY-----';
      const encryptor = new JSEncrypt();
      encryptor.setPublicKey(publicKey);
      const plainText= "This is a encrypting string";
      const encrypted = encryptor.encrypt(plainText);
      #the encrypted string is ready to send your server
Enter fullscreen mode Exit fullscreen mode

Basic initialization in Laravel

      $encryptedData = $request->input('data');
      #save your private key in this path file also you can create path yourself
      $privateKeyFile= file_get_contents(storage_path('app/keys/private.pem'));

      $privateKey = openssl_pkey_get_private($privateKeyFile);
      $encrypted = base64_decode($encryptedData);
      openssl_private_decrypt($encrypted, $decrypted, $privateKey);
      return response()->json(['decrypted' => $decrypted]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)