Home > Article > Backend Development > javascript - What method does js use to encrypt the data of ajax post and transmit it to php for decryption?
Since I don’t want to transmit plain text when doing ajax post, I want to use js to encrypt a js object into a string or binary string for transmission, but I don’t know how to encrypt it, and this encrypted string needs to be in php Decrypt it on the end, and the decrypted data is preferably a php array. Does anyone have such a need? Do you know how to achieve this?
Since I don’t want to transmit plain text when doing ajax post, I want to use js to encrypt a js object into a string or binary string for transmission, but I don’t know how to encrypt it, and this encrypted string needs to be in php Decrypt it on the end, and the decrypted data is preferably a php array. Does anyone have such a need? Do you know how to achieve this?
First of all, crypto-js can solve your problem. Choose a symmetric encryption algorithm (such as AES-256-CBC), use AES + password to encrypt on the PHP side, and use AES + password to decrypt on the js side - but this does not make much sense because your passwords are already expressed in plain text in the js code. .
So if your purpose is to transmit untext, it is recommended that you implement asymmetric encryption from the transport layer. The simplest way is to change the server protocol from HTTP to HTTPs.
You can use an asymmetric encryption algorithm, encrypting with the public key in the browser and decrypting with the private key on the server side. The jsencrypt project supports RSA encryption. You only need to use openssl
to generate a key pair, and then put the public key into the page. PHP can decrypt using the openssl series of functions.
The encrypted and decrypted data are all strings. If you want to get the array, you can create an object in JS, then adjust JSON.stringify
and then encrypt it. What PHP decodes is a JSON string, and you can use the json_decode function to decode it to get an array.