index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. var Buffer = require('safe-buffer').Buffer
  2. var createHash = require('create-hash')
  3. var stream = require('readable-stream')
  4. var inherits = require('inherits')
  5. var sign = require('./sign')
  6. var verify = require('./verify')
  7. var algorithms = require('./algorithms.json')
  8. Object.keys(algorithms).forEach(function (key) {
  9. algorithms[key].id = Buffer.from(algorithms[key].id, 'hex')
  10. algorithms[key.toLowerCase()] = algorithms[key]
  11. })
  12. function Sign (algorithm) {
  13. stream.Writable.call(this)
  14. var data = algorithms[algorithm]
  15. if (!data) throw new Error('Unknown message digest')
  16. this._hashType = data.hash
  17. this._hash = createHash(data.hash)
  18. this._tag = data.id
  19. this._signType = data.sign
  20. }
  21. inherits(Sign, stream.Writable)
  22. Sign.prototype._write = function _write (data, _, done) {
  23. this._hash.update(data)
  24. done()
  25. }
  26. Sign.prototype.update = function update (data, enc) {
  27. if (typeof data === 'string') data = Buffer.from(data, enc)
  28. this._hash.update(data)
  29. return this
  30. }
  31. Sign.prototype.sign = function signMethod (key, enc) {
  32. this.end()
  33. var hash = this._hash.digest()
  34. var sig = sign(hash, key, this._hashType, this._signType, this._tag)
  35. return enc ? sig.toString(enc) : sig
  36. }
  37. function Verify (algorithm) {
  38. stream.Writable.call(this)
  39. var data = algorithms[algorithm]
  40. if (!data) throw new Error('Unknown message digest')
  41. this._hash = createHash(data.hash)
  42. this._tag = data.id
  43. this._signType = data.sign
  44. }
  45. inherits(Verify, stream.Writable)
  46. Verify.prototype._write = function _write (data, _, done) {
  47. this._hash.update(data)
  48. done()
  49. }
  50. Verify.prototype.update = function update (data, enc) {
  51. if (typeof data === 'string') data = Buffer.from(data, enc)
  52. this._hash.update(data)
  53. return this
  54. }
  55. Verify.prototype.verify = function verifyMethod (key, sig, enc) {
  56. if (typeof sig === 'string') sig = Buffer.from(sig, enc)
  57. this.end()
  58. var hash = this._hash.digest()
  59. return verify(sig, hash, key, this._signType, this._tag)
  60. }
  61. function createSign (algorithm) {
  62. return new Sign(algorithm)
  63. }
  64. function createVerify (algorithm) {
  65. return new Verify(algorithm)
  66. }
  67. module.exports = {
  68. Sign: createSign,
  69. Verify: createVerify,
  70. createSign: createSign,
  71. createVerify: createVerify
  72. }