native-password-auth.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const PluginAuth = require('./plugin-auth');
  3. const Crypto = require('crypto');
  4. /**
  5. * Standard authentication plugin
  6. */
  7. class NativePasswordAuth extends PluginAuth {
  8. constructor(packSeq, compressPackSeq, pluginData, resolve, reject, multiAuthResolver) {
  9. super(resolve, reject, multiAuthResolver);
  10. this.pluginData = pluginData;
  11. this.sequenceNo = packSeq;
  12. this.compressSequenceNo = compressPackSeq;
  13. }
  14. start(out, opts, info) {
  15. //seed is ended with a null byte value.
  16. const data = this.pluginData.slice(0, 20);
  17. let authToken = NativePasswordAuth.encryptPassword(opts.password, data, 'sha1');
  18. out.startPacket(this);
  19. if (authToken.length > 0) {
  20. out.writeBuffer(authToken, 0, authToken.length);
  21. out.flushBuffer(true);
  22. } else {
  23. out.writeEmptyPacket(true);
  24. }
  25. this.emit('send_end');
  26. this.onPacketReceive = this.successSend;
  27. }
  28. static encryptPassword(password, seed, algorithm) {
  29. if (!password) return Buffer.alloc(0);
  30. let hash = Crypto.createHash(algorithm);
  31. let stage1 = hash.update(password, 'utf8').digest();
  32. hash = Crypto.createHash(algorithm);
  33. let stage2 = hash.update(stage1).digest();
  34. hash = Crypto.createHash(algorithm);
  35. hash.update(seed);
  36. hash.update(stage2);
  37. let digest = hash.digest();
  38. let returnBytes = Buffer.allocUnsafe(digest.length);
  39. for (let i = 0; i < digest.length; i++) {
  40. returnBytes[i] = stage1[i] ^ digest[i];
  41. }
  42. return returnBytes;
  43. }
  44. }
  45. module.exports = NativePasswordAuth;