forked from bcoin-org/bcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigest.js
120 lines (97 loc) · 2.26 KB
/
digest.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*!
* digest.js - hash functions for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module crypto.digest
*/
const assert = require('assert');
const crypto = require('crypto');
const native = require('../native').binding;
const POOL64 = Buffer.allocUnsafe(64);
/**
* Hash with chosen algorithm.
* @param {String} alg
* @param {Buffer} data
* @returns {Buffer}
*/
exports.hash = function hash(alg, data) {
return crypto.createHash(alg).update(data).digest();
};
/**
* Hash with ripemd160.
* @param {Buffer} data
* @returns {Buffer}
*/
exports.ripemd160 = function ripemd160(data) {
return exports.hash('ripemd160', data);
};
/**
* Hash with sha1.
* @param {Buffer} data
* @returns {Buffer}
*/
exports.sha1 = function sha1(data) {
return exports.hash('sha1', data);
};
/**
* Hash with sha256.
* @param {Buffer} data
* @returns {Buffer}
*/
exports.sha256 = function sha256(data) {
return exports.hash('sha256', data);
};
/**
* Hash with sha256 and ripemd160 (OP_HASH160).
* @param {Buffer} data
* @returns {Buffer}
*/
exports.hash160 = function hash160(data) {
return exports.ripemd160(exports.sha256(data));
};
/**
* Hash with sha256 twice (OP_HASH256).
* @param {Buffer} data
* @returns {Buffer}
*/
exports.hash256 = function hash256(data) {
return exports.sha256(exports.sha256(data));
};
/**
* Hash left and right hashes with hash256.
* @param {Buffer} left
* @param {Buffer} right
* @returns {Buffer}
*/
exports.root256 = function root256(left, right) {
const data = POOL64;
assert(left.length === 32);
assert(right.length === 32);
left.copy(data, 0);
right.copy(data, 32);
return exports.hash256(data);
};
/**
* Create an HMAC.
* @param {String} alg
* @param {Buffer} data
* @param {Buffer} key
* @returns {Buffer} HMAC
*/
exports.hmac = function hmac(alg, data, key) {
const ctx = crypto.createHmac(alg, key);
return ctx.update(data).digest();
};
if (native) {
exports.hash = native.hash;
exports.hmac = native.hmac;
exports.ripemd160 = native.ripemd160;
exports.sha1 = native.sha1;
exports.sha256 = native.sha256;
exports.hash160 = native.hash160;
exports.hash256 = native.hash256;
exports.root256 = native.root256;
}