Skip to content

Commit 874f820

Browse files
authored
fix: derive ed25519 public key from private key using node crypto (libp2p#300)
Create a private key object from the raw `Ed25519` private key and export it as a JWK to obtain the public key. Fixes libp2p#295
1 parent dfe6825 commit 874f820

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/keys/ed25519.ts

+19-4
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,25 @@ const SIGNATURE_BYTE_LENGTH = 64
1313
export { PUBLIC_KEY_BYTE_LENGTH as publicKeyLength }
1414
export { PRIVATE_KEY_BYTE_LENGTH as privateKeyLength }
1515

16-
function derivePublicKey (privateKey: Uint8Array) {
17-
const hash = crypto.createHash('sha512')
18-
hash.update(privateKey)
19-
return hash.digest().subarray(32)
16+
function derivePublicKey (privateKey: Uint8Array): Uint8Array {
17+
const keyObject = crypto.createPrivateKey({
18+
format: 'jwk',
19+
key: {
20+
crv: 'Ed25519',
21+
x: '',
22+
d: uint8arrayToString(privateKey, 'base64url'),
23+
kty: 'OKP'
24+
}
25+
})
26+
const jwk = keyObject.export({
27+
format: 'jwk'
28+
})
29+
30+
if (jwk.x == null || jwk.x === '') {
31+
throw new Error('Could not export JWK public key')
32+
}
33+
34+
return uint8arrayFromString(jwk.x, 'base64url')
2035
}
2136

2237
export async function generateKey () {

test/keys/ed25519.spec.ts

+9
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,15 @@ describe('ed25519', function () {
148148
expect(valid).to.eql(true)
149149
})
150150

151+
it('sign and verify from seed', async () => {
152+
const seed = new Uint8Array(32).fill(1)
153+
const seededkey = await crypto.keys.generateKeyPairFromSeed('Ed25519', seed)
154+
const data = uint8ArrayFromString('hello world')
155+
const sig = await seededkey.sign(data)
156+
const valid = await seededkey.public.verify(data, sig)
157+
expect(valid).to.eql(true)
158+
})
159+
151160
it('fails to verify for different data', async () => {
152161
const data = uint8ArrayFromString('hello world')
153162
const sig = await key.sign(data)

0 commit comments

Comments
 (0)