Skip to content

Commit

Permalink
fix: handle SimpleSigner privateKey 0x hex prefix by stripping it (#93)
Browse files Browse the repository at this point in the history
It is common to use 0x as a prefix in hex strings, some libs return private keys with that prefix, but SimpleSigner doesn't handle them.
  • Loading branch information
PeterTheOne authored May 29, 2020
1 parent 4d84198 commit 47595d3
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/SimpleSigner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ function leftpad(data: string, size = 64): string {
*/

function SimpleSigner(hexPrivateKey: string): Signer {
if (hexPrivateKey.startsWith('0x')) {
hexPrivateKey = hexPrivateKey.substring(2)
}
const privateKey: ec.KeyPair = secp256k1.keyFromPrivate(hexPrivateKey)
return async data => {
const { r, s, recoveryParam }: EC.Signature = privateKey.sign(sha256(data))
Expand Down
7 changes: 7 additions & 0 deletions src/__tests__/SimpleSigner-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ it('signs data', async () => {
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer(plaintext)).resolves.toMatchSnapshot()
})

const privateKey0x = '0x278a5de700e29faae8e40e366ec5012b5ec63d36ec77e8a2417154cc1d25383f'
it('signs data: privateKey with 0x prefix', async () => {
const signer2 = SimpleSigner(privateKey0x)
const plaintext = 'thequickbrownfoxjumpedoverthelazyprogrammer'
return await expect(signer2(plaintext)).resolves.toMatchSnapshot()
})
8 changes: 8 additions & 0 deletions src/__tests__/__snapshots__/SimpleSigner-test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,11 @@ Object {
"s": "c9e02ee61b64cf2fd623c8a1296125eaaa452b7d1a02c5079c1d1d75521ecf3b",
}
`;

exports[`signs data: privateKey with 0x prefix 1`] = `
Object {
"r": "8ecbdd2f0aabf8edb4ea191e828abaa5ba3b2c98c269f9442870af7e88413fd5",
"recoveryParam": 0,
"s": "c9e02ee61b64cf2fd623c8a1296125eaaa452b7d1a02c5079c1d1d75521ecf3b",
}
`;

0 comments on commit 47595d3

Please sign in to comment.