Error while using IPFS keypair for public key cryptography

Hello IPFS community,

I’m trying to share a small encrypted message between two nodes (say node1 wants to share a message with node2) using public key cryptography (i.e. node1 encrypts the data with node2’s public key and node2 decrypts it with their private key). For this, I’m trying to use the IPFS node’s own key pair. I’m following the procedure that’s very similar to the one mentioned in this gist.

To get the public key at node2, I’m using

let pub_key = (await

This key is then written to orbit-db, which is read by node1. The encryption process at node1’s side
usng the public key is:

// assume public key obtained from the orbit-db is stored in pub_key

pub_key = await p2pcrypto.keys.unmarshalPublicKey(Buffer.from(pub_key, 'base64'))

let publicKey = {
    n: Buffer.from(pub_key._key.n, 'base64'),
    e: Buffer.from(pub_key._key.e, 'base64'),

let usefulPubKey = new NodeRSA()

usefulPubKey.importKey(publicKey, 'components-public')

let cipher = usefulPubKey.encrypt(data)

return cipher;

This encrypted data is then read by node1, and is decrypted as follows:

let private_key = (await node.config.get("Identity"))["PrivKey"]
private_key = await p2pcrypto.keys.unmarshalPrivateKey(Buffer.from(private_key, 'base64'))

let usefulPrivKey = new NodeRSA();

    n: Buffer.from(private_key._key.n, 'base64'),
    e: Buffer.from(private_key._key.e, 'base64'),
    d: Buffer.from(private_key._key.d, 'base64'),
    p: Buffer.from(private_key._key.p, 'base64'),
    q: Buffer.from(private_key._key.q, 'base64'),
    dmp1: Buffer.from(private_key._key.dp, 'base64'),
    dmq1: Buffer.from(private_key._key.dq, 'base64'),
    coeff: Buffer.from(private_key._key.qi, 'base64'),
}, 'components');

let messageBytes = usefulPrivKey.decrypt(data)
let plain = messageBytes.toString()

return plain

The issue I’m facing is that sometime this works fine – the message is successfully decrypted back into the plaintext. But, other times I get this error:


Could anyone help me understand the issue here?

In case it helps, I’m using ‘crypto.subtle’ API, and doing the kind of stuff you’re talking about here:

The crypto API is in all web browsers, and just because of that and known browser compatibility that would be the API I’d use, but I’m not sure it’s available in NPM (non-browser uses)

Thanks, I’ll take a look