bn.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Generated by IcedCoffeeScript 1.7.1-c
  2. (function() {
  3. var BigInteger, mpi_byte_length, mpi_from_buffer, mpi_to_padded_octets, nbi, nbits, nbs, nbv, toMPI, _ref;
  4. _ref = require('bn'), nbv = _ref.nbv, nbi = _ref.nbi, BigInteger = _ref.BigInteger, nbits = _ref.nbits;
  5. nbs = function(s, base) {
  6. var r;
  7. if (base == null) {
  8. base = 10;
  9. }
  10. r = nbi();
  11. return r.fromString(s, base);
  12. };
  13. mpi_byte_length = function(bn) {
  14. return bn.toByteArray().length;
  15. };
  16. toMPI = function(bn) {
  17. var ba, hdr, size;
  18. ba = bn.toByteArray();
  19. size = (ba.length - 1) * 8 + nbits(ba[0]);
  20. hdr = new Buffer(2);
  21. hdr.writeUInt16BE(size, 0);
  22. return Buffer.concat([hdr, new Buffer(ba)]);
  23. };
  24. mpi_from_buffer = function(raw) {
  25. var err, hdr, i, n_bits, n_bytes;
  26. err = i = null;
  27. if (raw.length < 2) {
  28. err = new Error("need at least 2 bytes; got " + raw.length);
  29. } else {
  30. hdr = new Buffer(raw.slice(0, 2));
  31. raw = raw.slice(2);
  32. n_bits = hdr.readUInt16BE(0);
  33. n_bytes = Math.ceil(n_bits / 8);
  34. if (raw.length < n_bytes) {
  35. err = new Error("MPI said " + n_bytes + " bytes but only got " + raw.length);
  36. } else {
  37. i = nbi().fromBuffer(raw.slice(0, n_bytes));
  38. raw = raw.slice(n_bytes);
  39. }
  40. }
  41. return [err, i, raw, n_bytes + 2];
  42. };
  43. mpi_to_padded_octets = function(bn, base) {
  44. var ba, diff, i, n, pad;
  45. n = base.mpi_byte_length();
  46. ba = bn.toByteArray();
  47. diff = n - ba.length;
  48. pad = new Buffer((function() {
  49. var _i, _results;
  50. _results = [];
  51. for (i = _i = 0; 0 <= diff ? _i < diff : _i > diff; i = 0 <= diff ? ++_i : --_i) {
  52. _results.push(0);
  53. }
  54. return _results;
  55. })());
  56. return Buffer.concat([pad, new Buffer(ba)]);
  57. };
  58. exports.toMPI = toMPI;
  59. exports.nbs = nbs;
  60. exports.mpi_from_buffer = mpi_from_buffer;
  61. exports.mpi_to_padded_octets = mpi_to_padded_octets;
  62. BigInteger.prototype.to_mpi_buffer = function() {
  63. return toMPI(this);
  64. };
  65. BigInteger.prototype.mpi_byte_length = function() {
  66. return mpi_byte_length(this);
  67. };
  68. BigInteger.prototype.to_padded_octets = function(base) {
  69. return mpi_to_padded_octets(this, base);
  70. };
  71. }).call(this);