bn.iced 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. {nbv,nbi,BigInteger,nbits} = require 'bn'
  2. #=================================================================
  3. # Generate a BigInt from a string s, and a base.
  4. # @param {String} s the BigInt
  5. # @param {number} base the base that the string is in
  6. # @return {BigInteger} the result
  7. nbs = (s, base = 10) ->
  8. r = nbi()
  9. r.fromString s, base
  10. #================================================================
  11. mpi_byte_length = (bn) -> bn.toByteArray().length
  12. #================================================================
  13. #
  14. # @param {BitInteger} bn An input big integer
  15. # @return {Buffer} A buffer-representation of the multi-precision integer
  16. #
  17. toMPI = (bn) ->
  18. ba = bn.toByteArray()
  19. # The top byte isn't a full byte, so figure out how many bits it takes
  20. size = (ba.length - 1) * 8 + nbits(ba[0])
  21. hdr = new Buffer 2
  22. hdr.writeUInt16BE size, 0
  23. Buffer.concat [ hdr, new Buffer(ba) ]
  24. #================================================================
  25. mpi_from_buffer = (raw) ->
  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[0...2]
  31. raw = raw[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[0...n_bytes]
  38. raw = raw[n_bytes...]
  39. [err, i, raw, (n_bytes + 2) ]
  40. #================================================================
  41. mpi_to_padded_octets = (bn, base) ->
  42. n = base.mpi_byte_length()
  43. ba = bn.toByteArray()
  44. diff = (n - ba.length)
  45. pad = new Buffer(0 for i in [0...diff])
  46. Buffer.concat [ pad, new Buffer(ba) ]
  47. #================================================================
  48. exports.toMPI = toMPI
  49. exports.nbs = nbs
  50. exports.mpi_from_buffer = mpi_from_buffer
  51. exports.mpi_to_padded_octets = mpi_to_padded_octets
  52. # Monkey-patch the BigInteger prototyp, for convenience...
  53. BigInteger.prototype.to_mpi_buffer = () -> toMPI @
  54. BigInteger.prototype.mpi_byte_length = () -> mpi_byte_length @
  55. BigInteger.prototype.to_padded_octets = (base) -> mpi_to_padded_octets @, base
  56. #================================================================