ed-compat.js 2.3 KB

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