Skip to content

Commit

Permalink
fix: address #63; add padding to buffer for keys
Browse files Browse the repository at this point in the history
  • Loading branch information
OR13 committed Feb 6, 2021
1 parent 6a39e4c commit 98a8ff8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
20 changes: 20 additions & 0 deletions packages/secp256k1/src/__tests__/31-byte-private-keys.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

import * as keyUtils from '../keyUtils';

// Originally reported in:
// https://github.com/transmute-industries/did-key.js/issues/63
it('private keys MUST always be 32 bytes', async () => {
// this JWK generatetes 31 byte length private keys
const example = {
"kty": "EC",
"crv": "secp256k1",
"d": "H8IPdO0ZRDrma0Oc1ASGp4R-7ioP3HKC2o3dBYLHUg",
"x": "F0UpAkmilL3GafMgs_NMLqwGpUYPEnFphet8wS21jMg",
"y": "vTGyefjnlCj2-T7gYw3Det6m1UtDOfbB4CTzROlT6QA",
"kid": "y3hMPnp_oK9BM_V9vXu0aErpbzz0mDKe7xjEG44doUg"
}
const privateKeyBuffer = keyUtils.privateKeyUInt8ArrayFromJwk(example);
expect(privateKeyBuffer.length).toBe(32);
const privateKeyJwk = keyUtils.privateKeyJwkFromPrivateKeyHex(privateKeyBuffer.toString('hex'))
expect(privateKeyJwk).toEqual(example);
});
8 changes: 7 additions & 1 deletion packages/secp256k1/src/keyUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,13 @@ export const publicKeyHexFromJwk = (jwk: ISecp256k1PublicKeyJwk) => {
/** convert jwk to binary encoded private key */
export const privateKeyUInt8ArrayFromJwk = (jwk: ISecp256k1PrivateKeyJwk) => {
const privateKeyHex = privateKeyHexFromJwk(jwk);
return Buffer.from(privateKeyHex, 'hex');
let asBuffer = Buffer.from(privateKeyHex, 'hex');
let padding = 32 - asBuffer.length
while(padding){
asBuffer = Buffer.concat([Buffer.from('00', 'hex'), asBuffer]);
padding--;
}
return asBuffer;
};

/** convert jwk to binary encoded public key */
Expand Down

0 comments on commit 98a8ff8

Please sign in to comment.