Extract Sha512 to own file

This commit is contained in:
Nicholas Dudfield
2015-08-04 13:54:26 +07:00
parent 71d62fd58c
commit 828737f3bc
3 changed files with 41 additions and 42 deletions

View File

@@ -0,0 +1,27 @@
'use strict';
const hashjs = require('hash.js');
const BigNum = require('bn.js');
module.exports = class Sha512 {
constructor() {
this.hash = hashjs.sha512();
}
add(bytes) {
this.hash.update(bytes);
return this;
}
addU32(i) {
return this.add([(i >>> 24) & 0xFF, (i >>> 16) & 0xFF,
(i >>> 8) & 0xFF, i & 0xFF]);
}
finish() {
return this.hash.digest();
}
first256() {
return this.finish().slice(0, 32);
}
first256BN() {
return new BigNum(this.first256());
}
};

View File

@@ -1,7 +1,7 @@
'use strict';
const BigNum = require('bn.js');
const hashjs = require('hash.js');
const Sha512 = require('./sha512');
function isVirtual() {
throw new Error('virtual method not implemented ');
@@ -19,13 +19,6 @@ function cachedProperty(obj, computer) {
};
}
function arrayToHex(a) {
return a.map(function(byteValue) {
const hex = byteValue.toString(16).toUpperCase();
return hex.length > 1 ? hex : '0' + hex;
}).join('');
}
function toGenericArray(sequence) {
const generic = [];
for (let i = 0; i < sequence.length; i++) {
@@ -34,35 +27,11 @@ function toGenericArray(sequence) {
return generic;
}
function bytesToHex(bytes) {
return arrayToHex(bytes);
}
class Sha512 {
constructor() {
this.hash = hashjs.sha512();
}
add(bytes) {
this.hash.update(bytes);
return this;
}
addU32(i) {
return this.add([(i >>> 24) & 0xFF, (i >>> 16) & 0xFF,
(i >>> 8) & 0xFF, i & 0xFF]);
}
finish() {
return this.hash.digest();
}
first256() {
return this.finish().slice(0, 32);
}
first256BN() {
return new BigNum(this.first256());
}
}
function seedFromPhrase(phrase) {
return hashjs.sha512().update(phrase).digest().slice(0, 16);
function bytesToHex(a) {
return a.map(function(byteValue) {
const hex = byteValue.toString(16).toUpperCase();
return hex.length > 1 ? hex : '0' + hex;
}).join('');
}
function createAccountID(pubKeyBytes) {
@@ -71,13 +40,16 @@ function createAccountID(pubKeyBytes) {
return hash160;
}
function seedFromPhrase(phrase) {
return hashjs.sha512().update(phrase).digest().slice(0, 16);
}
module.exports = {
arrayToHex,
bytesToHex,
cachedProperty,
createAccountID,
isVirtual,
Sha512,
toGenericArray,
seedFromPhrase,
createAccountID
Sha512,
toGenericArray
};

View File

@@ -181,7 +181,7 @@ describe('K256Pair', function() {
it('can deterministically sign/verify message [' + i + ']', function() {
const message = [i];
const sig = key.sign(message);
assert.equal(utils.arrayToHex(sig), expected[i]);
assert.equal(utils.bytesToHex(sig), expected[i]);
assert(key.verify(message, sig));
});
}