简体   繁体   中英

Javascript and PHP Encryption/Decryption

Basically, I have an ajax form that carries login information, is there any way I can encrypt the password before it sends in ajax then decrypt it in php?

Or any other ways I should look at it?

Many thanks :)

There is no reason to do any encryption in JavaScript or PHP as the appropriate solution is to use SSL (HTTPS). Nowadays you can even get certificates which are trusted in all browsers for free so there's no reason for not using SSL.

If you cannot use SSL for some reason, you could get a JavaScript implementation of RSA so you can encrypt it locally but only your server is able to decrypt it again.

You could use RC4, since I know theres an implementation of it in PHP and Javascript. However, with any sort of encryption, you'd have to leave the key client side (so it can encrypt it), which means that anyone who has access to your page can get the key and decrypt it (thus defeating the point).

You might be better off either hashing it client-side (and then matching the hashes in PHP, if you don't need to know the password), or using Public-Private key encryption (like RSA), so that clients can encrypt, but not decrypt it.

For hashing, look at hash() and sha1 for Javascript .

And for RSA, check out this blog post http://www.sematopia.com/2008/10/rsa-encrypting-in-javascript-and-decrypting-in-php/

使用SSL证书并从您的AJAX表单通过HTTPS发送登录。

You can't in a secure manner. you should use https

You can do md5(password) in both JS and PHP, and then compare the encrypted passwords.

As username is not encrypted, you can use it to take the password from DB in PHP, and then encrypt it.

Best way to do that is:

  • generate a uniqid , save it in $_SESSION['crypt_key'] , and send it as a hidden input on the ajax form;
  • encrypt in JS using md5(crypt_key + password) before sending it;
  • encrypt in PHP using md5($_SESSION['crypt_key'] . $password) and compare them. This way, every request will transfer an unpredictable crypted password.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM