Converting between Ed25519 key and peerID #2379
-
What is the easiest and simplest way to obtain these in js-libp2p? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
A PeerId is a multihash of a protobuf struct that contains the key In the case of RSA For Ed25519 and Secp256k1 keys So for import { keysPBM } from '@libp2p/crypto/keys'
import { createPeerId } from '@libp2p/peer-id'
import { identity } from 'multiformats/hashes/identity'
import * as Digest from 'multiformats/hashes/digest'
// these are the raw key bytes
const bytes = Uint8Array.from([ /* 32 bytes */ ])
// the raw key bytes are stored in a protobuf struct
const protobuf = keysPBM.PublicKey.encode({
Type: keysPBM.KeyType.Ed25519,
Data: bytes
})
// the multihash is an identity hash where the digest is the serialized protobuf struct
const multihash = Digest.create(identity.code, protobuf)
// create the PeerId object from the multihash
const peerId = createPeerId({
type: 'Ed25519',
multihash
})
// if using TypeScript you can disambiguate `PeerId` to `Ed25519PeerId` using the `.type` field:
if (peerId.type === 'Ed25519') {
// type of peerId is now `Ed25519PeerId`
} else {
throw new Error('Unexpected PeerId type')
} To turn a string into a import { peerIdFromString } from '@libp2p/peer-id'
import { unmarshalPublicKey } from '@libp2p/crypto/keys'
const peerId = peerIdFromString('123Foo')
const publicKey = unmarshalPublicKey(peerId.publicKey)
// if using TypeScript you can disambiguate `PublicKey` to `Ed25519PublicKey` using the `.type` field:
if (publicKey.type === 'Ed25519') {
// type of publicKey is now `Ed25519PublicKey`
} else {
throw new Error('Unexpected PublicKey type')
} |
Beta Was this translation helpful? Give feedback.
A PeerId is a multihash of a protobuf struct that contains the key
Type
and aData
field.In the case of RSA
Data
is the public key encoded as PKIX/X.509 in ASN1 DER format and the multihash is the sha256 hash of the serialized protobuf bytes.For Ed25519 and Secp256k1 keys
Data
is the raw public key bytes and the multihash is the identity hash, that is the multihash digest contains the actual serialized protobuf struct.So for
Ed25519
keys we can recreate the multihash with: