ADD check so sign() only signs hashes

state-channel
pubkey 7 years ago
parent 1cbcfbc796
commit 8f45cd5639
  1. 6
      README.md
  2. 5
      src/sign.js
  3. 21
      test/unit.test.js

@ -82,12 +82,14 @@ Derives the ethereum-address from the publicKey.
### sign()
Signs the message with the privateKey. Returns the signature as hex-string.
Signs the hash with the privateKey. Returns the signature as hex-string.
```javascript
const message = 'foobar';
const messageHash = EthCrypto.hash.keccak256(message);
const signature = EthCrypto.sign(
'0x107be946709e41b7895eea9f2dacf998a0a9124acbb786f0fd1a826101581a07', // privateKey
'foobar' // message
messageHash // hash of message
);
// > '0xc04b809d8f33c46ff80c44ba58e866ff0d5..'
```

@ -1,4 +1,5 @@
import Account from 'eth-lib/lib/account';
import * as util from './util';
/**
* signs the given message
@ -7,6 +8,10 @@ import Account from 'eth-lib/lib/account';
* @return {string} hexString
*/
export default function sign(privateKey, hash) {
hash = util.addTrailing0x(hash);
if (hash.length !== 66)
throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
const signature = Account.sign(hash, privateKey);
return signature;
}

@ -56,7 +56,8 @@ describe('unit.test.js', () => {
describe('positive', () => {
it('should sign the data', () => {
const message = AsyncTestUtil.randomString(12);
const signature = EthCrypto.sign(TEST_DATA.privateKey, message);
const messageHash = EthCrypto.hash.keccak256(message);
const signature = EthCrypto.sign(TEST_DATA.privateKey, messageHash);
assert.equal(typeof signature, 'string');
assert.ok(signature.length > 10);
});
@ -71,14 +72,23 @@ describe('unit.test.js', () => {
)
);
});
it('should throw when non-hash given', ()=> {
assert.throws(
() => EthCrypto.sign(
TEST_DATA.privateKey,
AsyncTestUtil.randomString(5)
)
);
});
});
});
describe('.recover()', () => {
describe('positive', () => {
it('should return the correct address', () => {
const message = AsyncTestUtil.randomString(12);
const signature = EthCrypto.sign(TEST_DATA.privateKey, message);
const address = EthCrypto.recover(signature, message);
const messageHash = EthCrypto.hash.keccak256(message);
const signature = EthCrypto.sign(TEST_DATA.privateKey, messageHash);
const address = EthCrypto.recover(signature, messageHash);
assert.equal(address, TEST_DATA.address);
});
});
@ -87,8 +97,9 @@ describe('unit.test.js', () => {
describe('.recoverPublicKey()', () => {
it('should recover the correct key', async () => {
const message = AsyncTestUtil.randomString(12);
const signature = EthCrypto.sign(TEST_DATA.privateKey, message);
const publicKey = EthCrypto.recoverPublicKey(signature, message);
const messageHash = EthCrypto.hash.keccak256(message);
const signature = EthCrypto.sign(TEST_DATA.privateKey, messageHash);
const publicKey = EthCrypto.recoverPublicKey(signature, messageHash);
assert.equal(publicKey, TEST_DATA.publicKey);
});
});

Loading…
Cancel
Save