I have created several accounts in Hedera,
and have their PrivateKeys and PublicKeys available in the Hedera SDK.
I am able to use these to create signatures on data,
and verify signatures on data, as the SDK provide methods to do these.
However, I would like to perform public key encryption/ decryption operations on data. Is there a recommended way to do so?
Note: I am aware that the SDK does not provide these methods.
Thus, I am willing to use crypto from NodeJs or an npm dependency,
as long as it is interoperable with PrivateKeys and PublicKeys from the Hedera SDK.
The Setup is the crucial part to address your question.
If the private key associated with your Hedera account is ECDSA secp256k1,
then you will want to create an ECDH object from node:crypto,
and intialise it with the PrivateKey.
Subsequently Encryption and Decryption are pretty straightforward,
you'll simply need to follow the API from standard-ecies,
which accepts the ECDH object as its key representation.
Setup:
import crypto from 'node:crypto';
import ecies from 'standard-ecies';
const accountEcdh = crypto.createECDH('secp256k1');
accountEcdh.setPrivateKey(hederaSdkEcdsaPrivateKey.toBytesRaw());
Encryption:
const clearBuffer = Buffer.from(clearData, 'utf8');
const encryptedBufer = await ecies.encrypt(accountEcdh.getPublicKey(), buffer, {});
Decryption:
const decryptedBuffer = await ecies.decrypt(accountEcdh, encryptedBufer, {});
const decrypteData = Buffer.from(decryptedBuffer, 'utf8');
In addition to the above, ED25519 keys cannot be used for encryption/decryption, only signatures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With