Encrypt string in PHP and decrypt in Node.js

前端 未结 4 465
误落风尘
误落风尘 2020-12-01 18:53

I am sending data through insecure connection between Apache and Node.js servers. I need to encrypt data in PHP and decrypt in Node.js. I\'ve spent 2 days trying to get it t

4条回答
  •  [愿得一人]
    2020-12-01 19:30

    Based on @inieto answer i created two simple classes for encryption and decryption one for php and one for typescript that are easy to use. https://github.com/5imun/Endecryptor Just include/import them and you are ready to go. Example for php:

    #Include Endecryptor before using it
    $secret = 'hxXxVEVNa3S6OQdgltNoDkbZ10b0MkQV';
    $method = 'AES-256-CBC';
    $valid_request_TS_interval = 100; # in seconds
    $endecryptor = new Endecryptor($secret, $method, $valid_request_TS_interval );
    
    $original_message = '{"test":"Hello, World!"}';
    $endecryptor->encryptWithTS($original_message);
    
    echo "Encrypted message: $endecryptor->temp_encrypted\n";
    echo "Encrypted message hmac: $endecryptor->temp_hmac\n";
    
    if ( $endecryptor->decryptAndValidateTS( $endecryptor->temp_encrypted, $endecryptor->temp_hmac ) ) {
      echo "Original message:  $original_message\n";
      echo "Decrypted message: $endecryptor->temp_decrypted\n";
    } else {
      echo 'Description was not successful';
    }
    

    Result:

    Encrypted message: MjliMmM5NzljYWQ0YjA4Mw==ULxsH1juCOrieEkiRpHY1CMkKtvSvB5X+b8E9cOcQ7yYt+SUKj+I6FjaGvYjEldt
    Encrypted message: hmac: 5aa8f1b268dfef0dc2f48f1a25204e82
    Original  message:  {"test":"Hello, World!"}
    Decrypted message: {"test":"Hello, World!"}
    

提交回复
热议问题