In applications, there is often a need to encrypt and store user passwords. Saving passwords in clear text has a disadvantage: Once leaked, it will easily cause great losses, and may also cause losses to users and passwords of other websites (because most users use the same account and password on most websites ).
This leak may come from two aspects: hackers and operation and maintenance personnel committing theft.
In order to prevent the password plaintext from leaking, we need to irreversibly encrypt the password field saved in the database. To be precise, it is encrypted and then saved to the database.
Commonly used irreversible encryption algorithms include MD5 and SHA-1.
In NodeJS, they are extremely easy to use, just use the official built-in crypto
package:
var clearText = '123456'; // MD5 Hash require('crypto').createHash('md5').update(clearText).digest('hex'); // 'e10adc3949ba59abbe56e057f20f883e' // SHA-1 Hash require('crypto').createHash('sha1').update(clearText).digest('hex'); // '7c4a8d09ca3762af61e59520943dc26494f8941b'
When a user registers, the password submitted by the user is first irreversibly encrypted, and then the ciphertext is stored in the database.
When a user logs in, the password submitted by the user is first encrypted in the same way, and then compared with the ciphertext in the database to determine whether the password is correct.
Theoretically, there are countless passwords corresponding to the same hash value, but don’t worry too much about the risk of being hit, because in comparison, your web server and database may be vulnerable to flooding attacks Collapse first.
Related recommendations:
Enhance the security of user password storage and verification_PHP tutorial
jquery.cookie.js method to implement the function of saving passwords for user login_ jquery
The above is the detailed content of NodeJS implements irreversible encryption and password saving. For more information, please follow other related articles on the PHP Chinese website!