選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

sha.js 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
  3. * in FIPS PUB 180-1
  4. * This source code is derived from sha1.js of the same repository.
  5. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
  6. * operation was added.
  7. */
  8. var inherits = require('inherits')
  9. var Hash = require('./hash')
  10. var Buffer = require('safe-buffer').Buffer
  11. var K = [
  12. 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
  13. ]
  14. var W = new Array(80)
  15. function Sha () {
  16. this.init()
  17. this._w = W
  18. Hash.call(this, 64, 56)
  19. }
  20. inherits(Sha, Hash)
  21. Sha.prototype.init = function () {
  22. this._a = 0x67452301
  23. this._b = 0xefcdab89
  24. this._c = 0x98badcfe
  25. this._d = 0x10325476
  26. this._e = 0xc3d2e1f0
  27. return this
  28. }
  29. function rotl5 (num) {
  30. return (num << 5) | (num >>> 27)
  31. }
  32. function rotl30 (num) {
  33. return (num << 30) | (num >>> 2)
  34. }
  35. function ft (s, b, c, d) {
  36. if (s === 0) return (b & c) | ((~b) & d)
  37. if (s === 2) return (b & c) | (b & d) | (c & d)
  38. return b ^ c ^ d
  39. }
  40. Sha.prototype._update = function (M) {
  41. var W = this._w
  42. var a = this._a | 0
  43. var b = this._b | 0
  44. var c = this._c | 0
  45. var d = this._d | 0
  46. var e = this._e | 0
  47. for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
  48. for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
  49. for (var j = 0; j < 80; ++j) {
  50. var s = ~~(j / 20)
  51. var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
  52. e = d
  53. d = c
  54. c = rotl30(b)
  55. b = a
  56. a = t
  57. }
  58. this._a = (a + this._a) | 0
  59. this._b = (b + this._b) | 0
  60. this._c = (c + this._c) | 0
  61. this._d = (d + this._d) | 0
  62. this._e = (e + this._e) | 0
  63. }
  64. Sha.prototype._hash = function () {
  65. var H = Buffer.allocUnsafe(20)
  66. H.writeInt32BE(this._a | 0, 0)
  67. H.writeInt32BE(this._b | 0, 4)
  68. H.writeInt32BE(this._c | 0, 8)
  69. H.writeInt32BE(this._d | 0, 12)
  70. H.writeInt32BE(this._e | 0, 16)
  71. return H
  72. }
  73. module.exports = Sha