This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathhash.js
85 lines (65 loc) · 2.12 KB
/
hash.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use strict';
var crypto = require('crypto');
var BufferUtil = require('../util/buffer');
var $ = require('../util/preconditions');
var Hash = module.exports;
Hash.sha1 = function(buf) {
$.checkArgument(BufferUtil.isBuffer(buf));
return crypto.createHash('sha1').update(buf).digest();
};
Hash.sha1.blocksize = 512;
Hash.sha256 = function(buf) {
$.checkArgument(BufferUtil.isBuffer(buf));
return crypto.createHash('sha256').update(buf).digest();
};
Hash.sha256.blocksize = 512;
Hash.sha256sha256 = function(buf) {
$.checkArgument(BufferUtil.isBuffer(buf));
return Hash.sha256(Hash.sha256(buf));
};
Hash.ripemd160 = function(buf) {
$.checkArgument(BufferUtil.isBuffer(buf));
return crypto.createHash('ripemd160').update(buf).digest();
};
Hash.sha256ripemd160 = function(buf) {
$.checkArgument(BufferUtil.isBuffer(buf));
return Hash.ripemd160(Hash.sha256(buf));
};
Hash.sha512 = function(buf) {
$.checkArgument(BufferUtil.isBuffer(buf));
return crypto.createHash('sha512').update(buf).digest();
};
Hash.sha512.blocksize = 1024;
Hash.hmac = function(hashf, data, key) {
//http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
//http://tools.ietf.org/html/rfc4868#section-2
$.checkArgument(BufferUtil.isBuffer(data));
$.checkArgument(BufferUtil.isBuffer(key));
$.checkArgument(hashf.blocksize);
var blocksize = hashf.blocksize / 8;
if (key.length > blocksize) {
key = hashf(key);
} else if (key < blocksize) {
var fill = Buffer.alloc(blocksize);
fill.fill(0);
key.copy(fill);
key = fill;
}
var o_key = Buffer.alloc(blocksize);
o_key.fill(0x5c);
var i_key = Buffer.alloc(blocksize);
i_key.fill(0x36);
var o_key_pad = Buffer.alloc(blocksize);
var i_key_pad = Buffer.alloc(blocksize);
for (var i = 0; i < blocksize; i++) {
o_key_pad[i] = o_key[i] ^ key[i];
i_key_pad[i] = i_key[i] ^ key[i];
}
return hashf(Buffer.concat([o_key_pad, hashf(Buffer.concat([i_key_pad, data]))]));
};
Hash.sha256hmac = function(data, key) {
return Hash.hmac(Hash.sha256, data, key);
};
Hash.sha512hmac = function(data, key) {
return Hash.hmac(Hash.sha512, data, key);
};