ed-compat.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2015 Joyent, Inc.
  2. module.exports = {
  3. Verifier: Verifier,
  4. Signer: Signer
  5. };
  6. var nacl;
  7. var stream = require('stream');
  8. var util = require('util');
  9. var assert = require('assert-plus');
  10. var Buffer = require('safer-buffer').Buffer;
  11. var Signature = require('./signature');
  12. function Verifier(key, hashAlgo) {
  13. if (nacl === undefined)
  14. nacl = require('tweetnacl');
  15. if (hashAlgo.toLowerCase() !== 'sha512')
  16. throw (new Error('ED25519 only supports the use of ' +
  17. 'SHA-512 hashes'));
  18. this.key = key;
  19. this.chunks = [];
  20. stream.Writable.call(this, {});
  21. }
  22. util.inherits(Verifier, stream.Writable);
  23. Verifier.prototype._write = function (chunk, enc, cb) {
  24. this.chunks.push(chunk);
  25. cb();
  26. };
  27. Verifier.prototype.update = function (chunk) {
  28. if (typeof (chunk) === 'string')
  29. chunk = Buffer.from(chunk, 'binary');
  30. this.chunks.push(chunk);
  31. };
  32. Verifier.prototype.verify = function (signature, fmt) {
  33. var sig;
  34. if (Signature.isSignature(signature, [2, 0])) {
  35. if (signature.type !== 'ed25519')
  36. return (false);
  37. sig = signature.toBuffer('raw');
  38. } else if (typeof (signature) === 'string') {
  39. sig = Buffer.from(signature, 'base64');
  40. } else if (Signature.isSignature(signature, [1, 0])) {
  41. throw (new Error('signature was created by too old ' +
  42. 'a version of sshpk and cannot be verified'));
  43. }
  44. assert.buffer(sig);
  45. return (nacl.sign.detached.verify(
  46. new Uint8Array(Buffer.concat(this.chunks)),
  47. new Uint8Array(sig),
  48. new Uint8Array(this.key.part.A.data)));
  49. };
  50. function Signer(key, hashAlgo) {
  51. if (nacl === undefined)
  52. nacl = require('tweetnacl');
  53. if (hashAlgo.toLowerCase() !== 'sha512')
  54. throw (new Error('ED25519 only supports the use of ' +
  55. 'SHA-512 hashes'));
  56. this.key = key;
  57. this.chunks = [];
  58. stream.Writable.call(this, {});
  59. }
  60. util.inherits(Signer, stream.Writable);
  61. Signer.prototype._write = function (chunk, enc, cb) {
  62. this.chunks.push(chunk);
  63. cb();
  64. };
  65. Signer.prototype.update = function (chunk) {
  66. if (typeof (chunk) === 'string')
  67. chunk = Buffer.from(chunk, 'binary');
  68. this.chunks.push(chunk);
  69. };
  70. Signer.prototype.sign = function () {
  71. var sig = nacl.sign.detached(
  72. new Uint8Array(Buffer.concat(this.chunks)),
  73. new Uint8Array(Buffer.concat([
  74. this.key.part.k.data, this.key.part.A.data])));
  75. var sigBuf = Buffer.from(sig);
  76. var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw');
  77. sigObj.hashAlgorithm = 'sha512';
  78. return (sigObj);
  79. };