Bcryptjs a better encryption module than Nodejs's own crypt
Environment: Nodejs 4.2.3/
Application of a password verification
Command line input: init ==> Command_init used to initialize the MongoDB database
Command line input: check [name] [password] ==> Command_check to verify the correctness of the password (name username, password user password)
' Use strict 'Const Bcrypt= Require (' Bcryptjs '); Const ReadLine= Require (' ReadLine '); Const Mongoose= Require ("Mongoose"); Const Schema=Mongoose. Schema;const Usershema=NewSchema ({name: {type:string, Required:true}, Password: {type:string, Required:true}}); const Usermodel= Mongoose.model (' User_ ', Usershema);functionConnect_mongodb () {Mongoose.connect (' Mongodb://localhost/test ');} Connect_mongodb (); //Connect DB//Crypt//produces a hash value based on the specified stringLet _hash_fn = (text, cb) = ={bcrypt.hash (text,10, CB);}; Const RL=Readline.createinterface ({input:process.stdin, output:process.stdout});functionCommand_init () {varname = ' Vison '; varPassword = ' vison1987 '; _HASH_FN (Password,function(Err, hashvalue) {if(ERR)returnConsole.log (ERR); Else{Let u=NewUsermodel ({name:name, password:hashvalue}); U.save (ERR)={console.log (err);}); } });}functionCommand_check (n, pwd) {Usermodel.findone ({name:n}, (Err,user)={ if(ERR)returnConsole.log (ERR); Else{bcrypt.compare (pwd, User.password,function(err,result) {if(ERR)returnConsole.log (ERR); Else{ if(Result = = =true) Console.log ("The password is correct"); ElseConsole.log (' Password error '); } }); } });} Rl.on (' Line ',function(cmd) {//multiple commands are separated by a space varCmdarray = Cmd.split (""); if(Cmdarray.length = = 1 ){ Switch(cmd) { Case"Init": Command_init (); Break; default:return;//Other command } }Else if(Cmdarray.length = = 3 ){ if(Cmdarray[0] = = = ' Check ') {Command_check (cmdarray[1],cmdarray[2]); }} rl.prompt ();}); Rl.setprompt ("V+>"); Rl.prompt ();
Start Mongod server: Mongod--dbpath [Your datebase Path]
Operation Result:
Nodejs Encryption Module BCRYPTJS application