Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. let bcrypt = require('bcrypt-nodejs');
  2.  
  3. let password = "hello";
  4. let stored_hash = "";
  5.  
  6. // first generate a random salt
  7. function genSalt(password) {
  8. return new Promise((resolve,reject) => {
  9. bcrypt.genSalt(10,function(err,salt) {
  10. if (err) {
  11. reject(err);
  12. }
  13. else {
  14. resolve({
  15. salt:salt,
  16. password:password
  17. });
  18. }
  19. });
  20. });
  21. }
  22.  
  23. // hash the password with the salt
  24. function genHash(salt,password) {
  25. return new Promise((resolve,reject) => {
  26. bcrypt.hash(password,salt,null,function(err,hash) {
  27. if (err) {
  28. reject(err);
  29. }
  30. else {
  31. resolve({
  32. salt:salt,
  33. password:password,
  34. hash:hash
  35. });
  36. }
  37. });
  38. });
  39. }
  40.  
  41. // execute in sequence
  42. console.log("store");
  43. genSalt(password)
  44. .then(function(result) {
  45. return genHash(result.salt,result.password);
  46. })
  47. .then(function(result) {
  48. console.log('store hash in user profile :', result);
  49. stored_hash = result.hash;
  50. })
  51. .catch(function(err) {
  52. console.log(err);
  53. });
  54.  
  55. // =====================================================
  56. function lookupUser(user,passwd) {
  57. return new Promise((resolve,reject) => {
  58. // lookup the user in the stored database
  59. // in this case its not async so just resolve with the stored hash
  60. resolve({
  61. user:user,
  62. password:passwd,
  63. hash1:stored_hash
  64. })
  65. })
  66. }
  67.  
  68. function reHash(user,password,hash1) {
  69. let salt = hash1.substr(0,30);
  70. return new Promise((resolve,reject) => {
  71. bcrypt.hash(password,salt,null,function(err,hash2) {
  72. if (err) {
  73. reject(err);
  74. }
  75. else {
  76. resolve({
  77. user:user,
  78. salt:salt,
  79. password:password,
  80. hash1:hash1, // stored hash
  81. hash2:hash2 // generated hash
  82. });
  83. }
  84. });
  85. });
  86. }
  87.  
  88. // lookup and verify
  89. setTimeout(function() {
  90. console.log("verify");
  91. lookupUser("joe",password)
  92. .then(function(result) {
  93. return reHash(result.user,result.password,result.hash1);
  94. })
  95. .then(function(result) {
  96. console.log(result.hash1);
  97. console.log(result.hash2);
  98. if (result.hash1 === result.hash2) {
  99. console.log('verified');
  100. }
  101. else {
  102. console.log('failed');
  103. }
  104. })
  105. .catch(function(err) {
  106. console.log(err);
  107. });
  108. },1000);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement