wallet-core/node_modules/create-hmac/browser.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-05-24 15:10:37 +02:00
'use strict'
2017-05-03 15:35:00 +02:00
var inherits = require('inherits')
2017-05-24 15:10:37 +02:00
var Legacy = require('./legacy')
var Base = require('cipher-base')
var Buffer = require('safe-buffer').Buffer
var md5 = require('create-hash/md5')
var RIPEMD160 = require('ripemd160')
2017-05-03 15:35:00 +02:00
2017-05-24 15:10:37 +02:00
var sha = require('sha.js')
2017-05-03 15:35:00 +02:00
2017-05-24 15:10:37 +02:00
var ZEROS = Buffer.alloc(128)
2017-05-03 15:35:00 +02:00
2017-05-24 15:10:37 +02:00
function Hmac (alg, key) {
Base.call(this, 'digest')
2017-05-03 15:35:00 +02:00
if (typeof key === 'string') {
2017-05-24 15:10:37 +02:00
key = Buffer.from(key)
2017-05-03 15:35:00 +02:00
}
var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
this._alg = alg
this._key = key
if (key.length > blocksize) {
2017-05-24 15:10:37 +02:00
var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
key = hash.update(key).digest()
2017-05-03 15:35:00 +02:00
} else if (key.length < blocksize) {
key = Buffer.concat([key, ZEROS], blocksize)
}
2017-05-24 15:10:37 +02:00
var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
var opad = this._opad = Buffer.allocUnsafe(blocksize)
2017-05-03 15:35:00 +02:00
for (var i = 0; i < blocksize; i++) {
ipad[i] = key[i] ^ 0x36
opad[i] = key[i] ^ 0x5C
}
2017-05-24 15:10:37 +02:00
this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
this._hash.update(ipad)
2017-05-03 15:35:00 +02:00
}
2017-05-24 15:10:37 +02:00
inherits(Hmac, Base)
2017-05-03 15:35:00 +02:00
2017-05-24 15:10:37 +02:00
Hmac.prototype._update = function (data) {
2017-05-03 15:35:00 +02:00
this._hash.update(data)
}
2017-05-24 15:10:37 +02:00
Hmac.prototype._final = function () {
2017-05-03 15:35:00 +02:00
var h = this._hash.digest()
2017-05-24 15:10:37 +02:00
var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
return hash.update(this._opad).update(h).digest()
2017-05-03 15:35:00 +02:00
}
2017-05-24 15:10:37 +02:00
module.exports = function createHmac (alg, key) {
alg = alg.toLowerCase()
if (alg === 'rmd160' || alg === 'ripemd160') {
return new Hmac('rmd160', key)
}
if (alg === 'md5') {
return new Legacy(md5, key)
}
2017-05-03 15:35:00 +02:00
return new Hmac(alg, key)
}