-
Notifications
You must be signed in to change notification settings - Fork 51
Question: Key type returned by crypto.keys.unmarshalPublicKey
#184
Description
In a web app I've recently built, I am generating RSA keys using the PeerID
library and then using those keys to encrypt and decrypt messages sent via libp2p.dialProtocol
between two browser-based libp2p nodes. The basic flow for passing the public between the two nodes is as follows:
- Node 1: create peerID using
PeerID.create({keyType:'RSA'})
and then start up a node using that generated peerID - Node 1: Present
libp2p.peerId.toJSON().pubKey
as a QR code - Node 2: Read the string of Node 1's public key and convert to PeerID using
PeerID.createFromPubKey(node1PublicKey)
- Node 2: Derive Node 1's public key using
libp2p-crypto.keys.unmarshalPublicKey(node1.peerId.marshalPubKey())
- Node 2: Typecast the derived node1 public key to an
RsaPublicKey
- Node 2: Encrypt messages using
node1publickey.encrypt(...message...)
- Node 1: Derive
RsaPrivateKey
from node 1's peerId usingcrypto.keys.unmarshalPrivateKey
- Node 2: Decrypt messages using the derived
RsaPrivateKey
This all works as outlined here. I can link to the specific code as needed but it's still in pretty rough form in my repo.
The issue I'm finding is that Typescript tells me that crypto.keys.unmarshalPublicKey
returns a key of Crypto.PublicKey
which doesn't expose the encrypt
and decrypt
methods. I can use //@ts-ignore
and everything works as I outlined above but if I use crypto.keys.supportedKeys.rsa.unmarshalRsaPublicKey
to satisfy Typescript where I use crypto.keys.unmarshalPublicKey
above, I get this error Error: Cannot read public key. ASN.1 object does not contain an RSAPublicKey.
and the app crashes, even though peerID I'm generating the public key from has the RsaPublicKey
property when I inspect it in the browser console.
I'm not sure if there's a better way to get at what I need or if I'm doing something wrong but why would crypto.keys.unmarshalPublicKey
successfully derive a key and not the crypto.keys.supportedKeys.rsa.unmarshallRsaPublicKey
method? Alternatively, is there a possible improvement to crypto.keys.unmarshalPublicKey/PrivateKey
where we could specify the key type as a parameter in the method so that it would return whichever of the supported key types (RSA/ed25519/secp256k1) so library users could make use of the full set of methods supported by each specific key type?