Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import elliptic from 'elliptic';
const defaultEncryptAlgorithm = 'secp256k1';
const defaultEc = elliptic.ec(defaultEncryptAlgorithm);
const keyPairs = {
[defaultEncryptAlgorithm]: defaultEc.genKeyPair()
};
class Sign {
/**
* static verify
* @param {string} algorithm ec algorithm
* @param {string} publicKey hex string, remote dapp public key
* @param {Buffer} msg message to be verified
* @param {string} signature remote dapp signature
* @return {boolean} result
*/
static verify(algorithm, publicKey, msg, signature) {
const remoteKeyPair = elliptic.ec(algorithm).keyFromPublic(publicKey, 'hex');
const r = signature.slice(0, 64);
const s = signature.slice(64, 128);
const recoveryParam = signature.slice(128);
const signatureObj = {
r,
s,
recoveryParam
};
try {
const result = remoteKeyPair.verify(msg, signatureObj);
return result;
} catch (e) {
return false;
}
}
constructor(algorithm, publicKey) {
if (!keyPairs[algorithm]) {
keyPairs[algorithm] = elliptic.ec(algorithm).genKeyPair();
}
this.keyPair = keyPairs[algorithm];
this.remoteKeyPair = elliptic.ec(algorithm).keyFromPublic(publicKey, 'hex');
}
/**
* sign message
* @param {Buffer} msg message to be signed
* @return {string} signature
*/
sign(msg) {
const signedMsg = this.keyPair.sign(msg);
return [signedMsg.r.toString(16, 64), signedMsg.s.toString(16, 64), `0${signedMsg.recoveryParam.toString()}`].join('');
}
/**
* verify signature
* @param {Buffer} msg message to be verified
* @param {string} signature hex string
* @return {boolean} result
*/
verify(msg, signature) {
const r = signature.slice(0, 64);
const s = signature.slice(64, 128);
const recoveryParam = signature.slice(128);
const signatureObj = {
r,
s,
recoveryParam
};
try {
const result = this.remoteKeyPair.verify(msg, signatureObj);
return result;
} catch (e) {
return false;
}
}
/**
* Gets the public key.
* @returns {string} The public key.
*/
getPublicKey() {
return this.keyPair.getPublic().encode('hex');
}
}
export default Sign;
|