Skip to content

Instantly share code, notes, and snippets.

@dsphinx
Forked from ve3/Encryption.js
Created April 11, 2020 06:05
Show Gist options
  • Save dsphinx/111af08dae4abfddc6a3a11df8472c34 to your computer and use it in GitHub Desktop.
Save dsphinx/111af08dae4abfddc6a3a11df8472c34 to your computer and use it in GitHub Desktop.

Revisions

  1. @ve3 ve3 revised this gist Jun 3, 2019. 1 changed file with 17 additions and 18 deletions.
    35 changes: 17 additions & 18 deletions test-js.php
    Original file line number Diff line number Diff line change
    @@ -17,29 +17,28 @@
    <script src="crypto-js.js"></script><!-- https://github.com/brix/crypto-js/releases crypto-js.js can be download from here -->
    <script src="Encryption.js"></script>
    <script>
    var readableString = '<?php echo $readableString; ?>';
    var nonceValue = '<?php echo $nonceValue; ?>';
    var encryptedString = '<?php echo $encryptedString; ?>';

    var readableString = '<?php echo $readableString; ?>';
    var nonceValue = '<?php echo $nonceValue; ?>';
    var encryptedString = '<?php echo $encryptedString; ?>';

    // on page loaded.
    jQuery(document).ready(function($) {
    let encryption = new Encryption();
    var encrypted = encryption.encrypt(readableString, nonceValue);
    console.log(encrypted);
    // on page loaded.
    jQuery(document).ready(function($) {
    let encryption = new Encryption();
    var encrypted = encryption.encrypt(readableString, nonceValue);
    console.log(encrypted);

    var decrypted = encryption.decrypt(encrypted, nonceValue);
    console.log(decrypted);
    var decrypted = encryption.decrypt(encrypted, nonceValue);
    console.log(decrypted);

    var decryptedOldString = encryption.decrypt(encryptedString, nonceValue);
    console.log(decryptedOldString);
    var decryptedOldString = encryption.decrypt(encryptedString, nonceValue);
    console.log(decryptedOldString);


    $('.resultPlaceholder').html('readable string: '+readableString+'<br>');
    $('.resultPlaceholder').append('encrypted: '+encrypted+'<br>');
    $('.resultPlaceholder').append('decrypted: '+decrypted+'<br>');
    $('.resultPlaceholder').append('decrypted from old encrypted string: <strong>'+decryptedOldString+'</strong><br>');
    });
    $('.resultPlaceholder').html('readable string: '+readableString+'<br>');
    $('.resultPlaceholder').append('encrypted: '+encrypted+'<br>');
    $('.resultPlaceholder').append('decrypted: '+decrypted+'<br>');
    $('.resultPlaceholder').append('decrypted from old encrypted string: <strong>'+decryptedOldString+'</strong><br>');
    });
    </script>
    </body>
    </html>
  2. @ve3 ve3 revised this gist Jun 1, 2019. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions Encryption.php
    Original file line number Diff line number Diff line change
    @@ -24,7 +24,7 @@ class Encryption
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string $encryptedString The encrypted string that is base64 encode.
    * @param string $key The key.
    * @return mixed Return original string value.
    * @return mixed Return original string value. Return null for failure get salt, iv.
    */
    public function decrypt($encryptedString, $key)
    {
    @@ -87,7 +87,8 @@ public function encrypt($string, $key)
    *
    * @return integer.
    */
    protected function encryptMethodLength() {
    protected function encryptMethodLength()
    {
    $number = filter_var($this->encryptMethod, FILTER_SANITIZE_NUMBER_INT);

    return intval(abs($number));
  3. @ve3 ve3 revised this gist Jun 1, 2019. 2 changed files with 2 additions and 1 deletion.
    1 change: 1 addition & 0 deletions Encryption.js
    Original file line number Diff line number Diff line change
    @@ -5,6 +5,7 @@
    *
    * @author Vee Winch.
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @link https://github.com/brix/crypto-js/releases crypto-js.js can be download from here.
    */
    class Encryption {

    2 changes: 1 addition & 1 deletion test-js.php
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@
    <div class="resultPlaceholder"></div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="crypto-js.js"></script>
    <script src="crypto-js.js"></script><!-- https://github.com/brix/crypto-js/releases crypto-js.js can be download from here -->
    <script src="Encryption.js"></script>
    <script>
    var readableString = '<?php echo $readableString; ?>';
  4. @ve3 ve3 revised this gist Apr 9, 2018. 4 changed files with 40 additions and 19 deletions.
    19 changes: 15 additions & 4 deletions Encryption.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,11 @@


    /**
    * Encryption class for encrypt/decrypt that works between programming languages.
    *
    * @author Vee Winch.
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    */
    class Encryption {


    @@ -40,19 +46,23 @@ class Encryption {
    * Decrypt string.
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @link https://stackoverflow.com/questions/25492179/decode-a-base64-string-using-cryptojs Crypto JS base64 encode/decode reference.
    * @param string encryptedString The encrypted string to be decrypt.
    * @param string key The secret key.
    * @param string key The key.
    * @return string Return decrypted string.
    */
    decrypt(encryptedString, key) {
    var json = JSON.parse(encryptedString);
    var json = JSON.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(encryptedString)));

    var salt = CryptoJS.enc.Hex.parse(json.salt);
    var iv = CryptoJS.enc.Hex.parse(json.iv);

    var encrypted = json.ciphertext;// no need to base64 decode.

    var iterations = parseInt(json.iterations);
    if (iterations <= 0) {
    iterations = 999;
    }
    var encryptMethodLength = (this.encryptMethodLength/4);// example: AES number is 256 / 4 = 64
    var hashKey = CryptoJS.PBKDF2(key, salt, {'hasher': CryptoJS.algo.SHA512, 'keySize': (encryptMethodLength/8), 'iterations': iterations});

    @@ -66,8 +76,9 @@ class Encryption {
    * Encrypt string.
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @link https://stackoverflow.com/questions/25492179/decode-a-base64-string-using-cryptojs Crypto JS base64 encode/decode reference.
    * @param string string The original string to be encrypt.
    * @param string key The secret key.
    * @param string key The key.
    * @return string Return encrypted string.
    */
    encrypt(string, key) {
    @@ -88,7 +99,7 @@ class Encryption {
    'iterations': iterations
    };

    return JSON.stringify(output);
    return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(JSON.stringify(output)));
    }// encrypt


    18 changes: 14 additions & 4 deletions Encryption.php
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,12 @@
    <?php


    /**
    * Encryption class for encrypt/decrypt that works between programming languages.
    *
    * @author Vee Winch.
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    */
    class Encryption
    {

    @@ -16,12 +23,12 @@ class Encryption
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string $encryptedString The encrypted string that is base64 encode.
    * @param string $key The secret key.
    * @param string $key The key.
    * @return mixed Return original string value.
    */
    public function decrypt($encryptedString, $key)
    {
    $json = json_decode($encryptedString, true);
    $json = json_decode(base64_decode($encryptedString), true);

    try {
    $salt = hex2bin($json["salt"]);
    @@ -33,6 +40,9 @@ public function decrypt($encryptedString, $key)
    $cipherText = base64_decode($json['ciphertext']);

    $iterations = intval(abs($json['iterations']));
    if ($iterations <= 0) {
    $iterations = 999;
    }
    $hashKey = hash_pbkdf2('sha512', $key, $salt, $iterations, ($this->encryptMethodLength() / 4));
    unset($iterations, $json, $salt);

    @@ -48,7 +58,7 @@ public function decrypt($encryptedString, $key)
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string $string The original string to be encrypt.
    * @param string $key The secret key.
    * @param string $key The key.
    * @return string Return encrypted string.
    */
    public function encrypt($string, $key)
    @@ -68,7 +78,7 @@ public function encrypt($string, $key)
    $output = ['ciphertext' => $encryptedString, 'iv' => bin2hex($iv), 'salt' => bin2hex($salt), 'iterations' => $iterations];
    unset($encryptedString, $iterations, $iv, $ivLength, $salt);

    return json_encode($output);
    return base64_encode(json_encode($output));
    }// encrypt


    12 changes: 6 additions & 6 deletions test-js.php
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,8 @@
    <?php
    $secretKey = 'mySecretKey';
    $nonceValue = 'nonce_value';// use nonce that generated while using OAuth.

    $readableString = 'asdf-ghjk-qwer-tyui';
    $encryptedString = '{"ciphertext":"PILpPBzj2rx+9sElY1H7saqILqBaxvt83n7+SpfBOPE=","iv":"637db026ca453df7665c1d7f48c60842","salt":"4957ddcd3d45e2999de3c9194aeccaf248e5b0df56f583399700424534c049fba27bdf8053c2ef41c54587273bb81d58a5ffb4fbd06de5ed348d86874369677fa0d001cfaeff24e26b766146cddfda2a4e81f46fc828cca9d28024e0cbe31f36697601086b0d51a5c4ce651b400b956d9778b1c09b89a62095c9f4407032e807a9a4fe4e55f19f64b1eadbf3350ca8b39b0c1d78474adb1a4b6caf94410c247163a1531d5410ca60b779c18c90b6e3fb554f26cd54668ce742f93c64a466455e481a9d9130344117a6d25368446a0fc8d4653d63596707459ab4ae79698fe23392e13f992cdd845151291454aa3798b437892a59cc0e014d46ee5986d5277071","iterations":999}';
    $encryptedString = 'eyJjaXBoZXJ0ZXh0IjoiNkRuSzRueVR5aERIQTVCdkF6SU9Mc0E0S1llUW5tZndvS0hIbERRMlE1VT0iLCJpdiI6IjNlNGU0YjFlNTBjNGRmODc2ZWExZTg3NjY3MDc4ZjBkIiwic2FsdCI6IjY0OWUxZDQ0NGNiZDc1YjBhODk2NmY2YTRjZTNjYzUzMmIyYTA4ZDQzZjlmYTQzNDRiOGU2MDFmNWIxODlkNzFjZGE3ZDc1YzU1YTBjMzNhMmM1ZWRlMjc5MTMxZTM5ZjNhYjgzY2JjNGQ5ZjIwYmY5YWE3YjdjN2MwNmVlMTZmNjJmYWEzMWU1MjFiMWZjNWFmZDcxMmRlNDQ3MWEyOTg3MDM0MzliODk0N2E0NGViOTMyMWFlMzI0ZWM2Zjg1ZjkwYmQzYzRmNjk5YzdmN2ViMTVhOGE0ZWExYjU1OGJmNWFiYjg5MzFjMjA5YTkzMWEwY2Q1NWM1NTgxMTRkNTY5NTIzZTk5OWMwZDA4Y2FiYmY4MzAzMTA0MzJkNzE2NmJlMDZlYzk3NjQzNzY1MzQ2NDI4YTM0ODM3MWUyOWRkNDU2ZTVmOGQ0NDgxZGVmZjY4M2FlOGYwOTJjODk3NjdhMzRhN2I0MWNlM2VlMDVlOWQ2ZDg4ZDI5MzVmZGM5MDUxY2VlZDhiYjllZDM5MzNjNjg2ODczZGNiOTJhZWI2MzBkMjNjODNhMjIyNTRjZDkxMDg4OTc4OWQ1MTI1MTc2MjQ2ZGYwOTQyODE5MTZlMmY4Y2RjYTU2MDEwMzEzZTM2NmE2ZDMyOTA4OGM3NzI5MWY3NDE3ODRiNTdmNTc1IiwiaXRlcmF0aW9ucyI6OTk5fQ==';
    ?>
    <!DOCTYPE html>
    <html>
    @@ -18,20 +18,20 @@
    <script src="Encryption.js"></script>
    <script>
    var readableString = '<?php echo $readableString; ?>';
    var secretKey = '<?php echo $secretKey; ?>';
    var nonceValue = '<?php echo $nonceValue; ?>';
    var encryptedString = '<?php echo $encryptedString; ?>';


    // on page loaded.
    jQuery(document).ready(function($) {
    let encryption = new Encryption();
    var encrypted = encryption.encrypt(readableString, secretKey);
    var encrypted = encryption.encrypt(readableString, nonceValue);
    console.log(encrypted);

    var decrypted = encryption.decrypt(encrypted, secretKey);
    var decrypted = encryption.decrypt(encrypted, nonceValue);
    console.log(decrypted);

    var decryptedOldString = encryption.decrypt(encryptedString, secretKey);
    var decryptedOldString = encryption.decrypt(encryptedString, nonceValue);
    console.log(decryptedOldString);


    10 changes: 5 additions & 5 deletions test-php.php
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,10 @@
    <?php
    require 'Encryption.php';

    $secretKey = 'mySecretKey';
    $nonceValue = 'nonce_value';// use nonce that generated while using OAuth.

    $readableString = 'asdf-ghjk-qwer-tyui';
    $encryptedString = '{"ciphertext":"PILpPBzj2rx+9sElY1H7saqILqBaxvt83n7+SpfBOPE=","iv":"637db026ca453df7665c1d7f48c60842","salt":"4957ddcd3d45e2999de3c9194aeccaf248e5b0df56f583399700424534c049fba27bdf8053c2ef41c54587273bb81d58a5ffb4fbd06de5ed348d86874369677fa0d001cfaeff24e26b766146cddfda2a4e81f46fc828cca9d28024e0cbe31f36697601086b0d51a5c4ce651b400b956d9778b1c09b89a62095c9f4407032e807a9a4fe4e55f19f64b1eadbf3350ca8b39b0c1d78474adb1a4b6caf94410c247163a1531d5410ca60b779c18c90b6e3fb554f26cd54668ce742f93c64a466455e481a9d9130344117a6d25368446a0fc8d4653d63596707459ab4ae79698fe23392e13f992cdd845151291454aa3798b437892a59cc0e014d46ee5986d5277071","iterations":999}';
    $encryptedString = 'eyJjaXBoZXJ0ZXh0IjoiNkRuSzRueVR5aERIQTVCdkF6SU9Mc0E0S1llUW5tZndvS0hIbERRMlE1VT0iLCJpdiI6IjNlNGU0YjFlNTBjNGRmODc2ZWExZTg3NjY3MDc4ZjBkIiwic2FsdCI6IjY0OWUxZDQ0NGNiZDc1YjBhODk2NmY2YTRjZTNjYzUzMmIyYTA4ZDQzZjlmYTQzNDRiOGU2MDFmNWIxODlkNzFjZGE3ZDc1YzU1YTBjMzNhMmM1ZWRlMjc5MTMxZTM5ZjNhYjgzY2JjNGQ5ZjIwYmY5YWE3YjdjN2MwNmVlMTZmNjJmYWEzMWU1MjFiMWZjNWFmZDcxMmRlNDQ3MWEyOTg3MDM0MzliODk0N2E0NGViOTMyMWFlMzI0ZWM2Zjg1ZjkwYmQzYzRmNjk5YzdmN2ViMTVhOGE0ZWExYjU1OGJmNWFiYjg5MzFjMjA5YTkzMWEwY2Q1NWM1NTgxMTRkNTY5NTIzZTk5OWMwZDA4Y2FiYmY4MzAzMTA0MzJkNzE2NmJlMDZlYzk3NjQzNzY1MzQ2NDI4YTM0ODM3MWUyOWRkNDU2ZTVmOGQ0NDgxZGVmZjY4M2FlOGYwOTJjODk3NjdhMzRhN2I0MWNlM2VlMDVlOWQ2ZDg4ZDI5MzVmZGM5MDUxY2VlZDhiYjllZDM5MzNjNjg2ODczZGNiOTJhZWI2MzBkMjNjODNhMjIyNTRjZDkxMDg4OTc4OWQ1MTI1MTc2MjQ2ZGYwOTQyODE5MTZlMmY4Y2RjYTU2MDEwMzEzZTM2NmE2ZDMyOTA4OGM3NzI5MWY3NDE3ODRiNTdmNTc1IiwiaXRlcmF0aW9ucyI6OTk5fQ==';
    ?>
    <!DOCTYPE html>
    <html>
    @@ -16,16 +16,16 @@
    <?php
    echo 'readable string: ' . $readableString . '<br>';
    $Encryption = new Encryption();
    $encrypted = $Encryption->encrypt($readableString, $secretKey);
    $encrypted = $Encryption->encrypt($readableString, $nonceValue);
    echo 'encrypted: ' . $encrypted . '<br>';

    echo "\n\n\n";
    echo '<hr>';
    echo "\n\n\n";

    $decrypted = $Encryption->decrypt($encrypted, $secretKey);
    $decrypted = $Encryption->decrypt($encrypted, $nonceValue);
    echo 'decrypted: ' . $decrypted . '<br>';
    $decrypted = $Encryption->decrypt($encryptedString, $secretKey);
    $decrypted = $Encryption->decrypt($encryptedString, $nonceValue);
    echo 'decrypted from old encrypted string: <strong>' . $decrypted . '</strong><br>';
    ?>
    </body>
  5. @ve3 ve3 revised this gist Apr 7, 2018. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions test-php.php
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,6 @@
    <?php
    require 'Encryption.php';

    $secretKey = 'mySecretKey';

    $readableString = 'asdf-ghjk-qwer-tyui';
  6. @ve3 ve3 revised this gist Apr 7, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion Encryption.js
    Original file line number Diff line number Diff line change
    @@ -44,7 +44,7 @@ class Encryption {
    * @param string key The secret key.
    * @return string Return decrypted string.
    */
    decrypt(encryptedString, key) {// not working with AES other than 256.
    decrypt(encryptedString, key) {
    var json = JSON.parse(encryptedString);

    var salt = CryptoJS.enc.Hex.parse(json.salt);
  7. @ve3 ve3 created this gist Apr 7, 2018.
    95 changes: 95 additions & 0 deletions Encryption.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,95 @@


    class Encryption {


    /**
    * @var integer Return encrypt method or Cipher method number. (128, 192, 256)
    */
    get encryptMethodLength() {
    var encryptMethod = this.encryptMethod;
    // get only number from string.
    // @link https://stackoverflow.com/a/10003709/128761 Reference.
    var aesNumber = encryptMethod.match(/\d+/)[0];
    return parseInt(aesNumber);
    }// encryptMethodLength


    /**
    * @var integer Return cipher method divide by 8. example: AES number 256 will be 256/8 = 32.
    */
    get encryptKeySize() {
    var aesNumber = this.encryptMethodLength;
    return parseInt(aesNumber / 8);
    }// encryptKeySize


    /**
    * @link http://php.net/manual/en/function.openssl-get-cipher-methods.php Refer to available methods in PHP if we are working between JS & PHP encryption.
    * @var string Cipher method.
    * Recommended AES-128-CBC, AES-192-CBC, AES-256-CBC
    * due to there is no `openssl_cipher_iv_length()` function in JavaScript
    * and all of these methods are known as 16 in iv_length.
    */
    get encryptMethod() {
    return 'AES-256-CBC';
    }// encryptMethod


    /**
    * Decrypt string.
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string encryptedString The encrypted string to be decrypt.
    * @param string key The secret key.
    * @return string Return decrypted string.
    */
    decrypt(encryptedString, key) {// not working with AES other than 256.
    var json = JSON.parse(encryptedString);

    var salt = CryptoJS.enc.Hex.parse(json.salt);
    var iv = CryptoJS.enc.Hex.parse(json.iv);

    var encrypted = json.ciphertext;// no need to base64 decode.

    var iterations = parseInt(json.iterations);
    var encryptMethodLength = (this.encryptMethodLength/4);// example: AES number is 256 / 4 = 64
    var hashKey = CryptoJS.PBKDF2(key, salt, {'hasher': CryptoJS.algo.SHA512, 'keySize': (encryptMethodLength/8), 'iterations': iterations});

    var decrypted = CryptoJS.AES.decrypt(encrypted, hashKey, {'mode': CryptoJS.mode.CBC, 'iv': iv});

    return decrypted.toString(CryptoJS.enc.Utf8);
    }// decrypt


    /**
    * Encrypt string.
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string string The original string to be encrypt.
    * @param string key The secret key.
    * @return string Return encrypted string.
    */
    encrypt(string, key) {
    var iv = CryptoJS.lib.WordArray.random(16);// the reason to be 16, please read on `encryptMethod` property.

    var salt = CryptoJS.lib.WordArray.random(256);
    var iterations = 999;
    var encryptMethodLength = (this.encryptMethodLength/4);// example: AES number is 256 / 4 = 64
    var hashKey = CryptoJS.PBKDF2(key, salt, {'hasher': CryptoJS.algo.SHA512, 'keySize': (encryptMethodLength/8), 'iterations': iterations});

    var encrypted = CryptoJS.AES.encrypt(string, hashKey, {'mode': CryptoJS.mode.CBC, 'iv': iv});
    var encryptedString = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

    var output = {
    'ciphertext': encryptedString,
    'iv': CryptoJS.enc.Hex.stringify(iv),
    'salt': CryptoJS.enc.Hex.stringify(salt),
    'iterations': iterations
    };

    return JSON.stringify(output);
    }// encrypt


    }
    99 changes: 99 additions & 0 deletions Encryption.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,99 @@
    <?php

    class Encryption
    {


    /**
    * @link http://php.net/manual/en/function.openssl-get-cipher-methods.php Available methods.
    * @var string Cipher method. Recommended AES-128-CBC, AES-192-CBC, AES-256-CBC
    */
    protected $encryptMethod = 'AES-256-CBC';


    /**
    * Decrypt string.
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string $encryptedString The encrypted string that is base64 encode.
    * @param string $key The secret key.
    * @return mixed Return original string value.
    */
    public function decrypt($encryptedString, $key)
    {
    $json = json_decode($encryptedString, true);

    try {
    $salt = hex2bin($json["salt"]);
    $iv = hex2bin($json["iv"]);
    } catch (Exception $e) {
    return null;
    }

    $cipherText = base64_decode($json['ciphertext']);

    $iterations = intval(abs($json['iterations']));
    $hashKey = hash_pbkdf2('sha512', $key, $salt, $iterations, ($this->encryptMethodLength() / 4));
    unset($iterations, $json, $salt);

    $decrypted= openssl_decrypt($cipherText , $this->encryptMethod, hex2bin($hashKey), OPENSSL_RAW_DATA, $iv);
    unset($cipherText, $hashKey, $iv);

    return $decrypted;
    }// decrypt


    /**
    * Encrypt string.
    *
    * @link https://stackoverflow.com/questions/41222162/encrypt-in-php-openssl-and-decrypt-in-javascript-cryptojs Reference.
    * @param string $string The original string to be encrypt.
    * @param string $key The secret key.
    * @return string Return encrypted string.
    */
    public function encrypt($string, $key)
    {
    $ivLength = openssl_cipher_iv_length($this->encryptMethod);
    $iv = openssl_random_pseudo_bytes($ivLength);

    $salt = openssl_random_pseudo_bytes(256);
    $iterations = 999;
    $hashKey = hash_pbkdf2('sha512', $key, $salt, $iterations, ($this->encryptMethodLength() / 4));

    $encryptedString = openssl_encrypt($string, $this->encryptMethod, hex2bin($hashKey), OPENSSL_RAW_DATA, $iv);

    $encryptedString = base64_encode($encryptedString);
    unset($hashKey);

    $output = ['ciphertext' => $encryptedString, 'iv' => bin2hex($iv), 'salt' => bin2hex($salt), 'iterations' => $iterations];
    unset($encryptedString, $iterations, $iv, $ivLength, $salt);

    return json_encode($output);
    }// encrypt


    /**
    * Get encrypt method length number (128, 192, 256).
    *
    * @return integer.
    */
    protected function encryptMethodLength() {
    $number = filter_var($this->encryptMethod, FILTER_SANITIZE_NUMBER_INT);

    return intval(abs($number));
    }// encryptMethodLength


    /**
    * Set encryption method.
    *
    * @link http://php.net/manual/en/function.openssl-get-cipher-methods.php Available methods.
    * @param string $cipherMethod
    */
    public function setCipherMethod($cipherMethod)
    {
    $this->encryptMethod = $cipherMethod;
    }// setCipherMethod


    }
    45 changes: 45 additions & 0 deletions test-js.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    <?php
    $secretKey = 'mySecretKey';

    $readableString = 'asdf-ghjk-qwer-tyui';
    $encryptedString = '{"ciphertext":"PILpPBzj2rx+9sElY1H7saqILqBaxvt83n7+SpfBOPE=","iv":"637db026ca453df7665c1d7f48c60842","salt":"4957ddcd3d45e2999de3c9194aeccaf248e5b0df56f583399700424534c049fba27bdf8053c2ef41c54587273bb81d58a5ffb4fbd06de5ed348d86874369677fa0d001cfaeff24e26b766146cddfda2a4e81f46fc828cca9d28024e0cbe31f36697601086b0d51a5c4ce651b400b956d9778b1c09b89a62095c9f4407032e807a9a4fe4e55f19f64b1eadbf3350ca8b39b0c1d78474adb1a4b6caf94410c247163a1531d5410ca60b779c18c90b6e3fb554f26cd54668ce742f93c64a466455e481a9d9130344117a6d25368446a0fc8d4653d63596707459ab4ae79698fe23392e13f992cdd845151291454aa3798b437892a59cc0e014d46ee5986d5277071","iterations":999}';
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    </head>
    <body>
    <div class="resultPlaceholder"></div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="crypto-js.js"></script>
    <script src="Encryption.js"></script>
    <script>
    var readableString = '<?php echo $readableString; ?>';
    var secretKey = '<?php echo $secretKey; ?>';
    var encryptedString = '<?php echo $encryptedString; ?>';


    // on page loaded.
    jQuery(document).ready(function($) {
    let encryption = new Encryption();
    var encrypted = encryption.encrypt(readableString, secretKey);
    console.log(encrypted);

    var decrypted = encryption.decrypt(encrypted, secretKey);
    console.log(decrypted);

    var decryptedOldString = encryption.decrypt(encryptedString, secretKey);
    console.log(decryptedOldString);


    $('.resultPlaceholder').html('readable string: '+readableString+'<br>');
    $('.resultPlaceholder').append('encrypted: '+encrypted+'<br>');
    $('.resultPlaceholder').append('decrypted: '+decrypted+'<br>');
    $('.resultPlaceholder').append('decrypted from old encrypted string: <strong>'+decryptedOldString+'</strong><br>');
    });
    </script>
    </body>
    </html>
    30 changes: 30 additions & 0 deletions test-php.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    <?php
    $secretKey = 'mySecretKey';

    $readableString = 'asdf-ghjk-qwer-tyui';
    $encryptedString = '{"ciphertext":"PILpPBzj2rx+9sElY1H7saqILqBaxvt83n7+SpfBOPE=","iv":"637db026ca453df7665c1d7f48c60842","salt":"4957ddcd3d45e2999de3c9194aeccaf248e5b0df56f583399700424534c049fba27bdf8053c2ef41c54587273bb81d58a5ffb4fbd06de5ed348d86874369677fa0d001cfaeff24e26b766146cddfda2a4e81f46fc828cca9d28024e0cbe31f36697601086b0d51a5c4ce651b400b956d9778b1c09b89a62095c9f4407032e807a9a4fe4e55f19f64b1eadbf3350ca8b39b0c1d78474adb1a4b6caf94410c247163a1531d5410ca60b779c18c90b6e3fb554f26cd54668ce742f93c64a466455e481a9d9130344117a6d25368446a0fc8d4653d63596707459ab4ae79698fe23392e13f992cdd845151291454aa3798b437892a59cc0e014d46ee5986d5277071","iterations":999}';
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    </head>
    <body>
    <?php
    echo 'readable string: ' . $readableString . '<br>';
    $Encryption = new Encryption();
    $encrypted = $Encryption->encrypt($readableString, $secretKey);
    echo 'encrypted: ' . $encrypted . '<br>';

    echo "\n\n\n";
    echo '<hr>';
    echo "\n\n\n";

    $decrypted = $Encryption->decrypt($encrypted, $secretKey);
    echo 'decrypted: ' . $decrypted . '<br>';
    $decrypted = $Encryption->decrypt($encryptedString, $secretKey);
    echo 'decrypted from old encrypted string: <strong>' . $decrypted . '</strong><br>';
    ?>
    </body>
    </html>