I’m trying to use a Hardware Security Module (HSM) to manually sign a Hedera transaction, but the Hedera JavaScript SDK requires me to pass my private key to the SDK for signing. Since my private key cannot leave the HSM and I can only use the HSM to sign transactions, I’m not sure how to proceed. Could someone please let me know how to do this? I couldn’t find any example code.
The flow I need to follow is:
Create a transaction
Serialize the transaction into transaction bytes
Pass the transaction bytes to the HSM for signing
Deserialize the signed transaction bytes back into a transaction object
Submit the signed transaction to the network
I tried running the following code but got INVALID_SIGNATURE error. I have made sure that the key is the correct one.
const { Client, AccountId, PrivateKey, TransferTransaction, Hbar, Transaction, } = require("@hashgraph/sdk"); async function main() { const client = Client.forTestnet(); const operatorPrivateKeyHex = "0xXXX"; const operatorId = AccountId.fromString("0.0.XXX"); const operatorKey = PrivateKey.fromString(operatorPrivateKeyHex); client.setOperator(operatorId, operatorPrivateKeyHex); let transaction = await new TransferTransaction() .addHbarTransfer(operatorId, Hbar.fromTinybars(-100)) .addHbarTransfer(AccountId.fromString("0.0.3"), Hbar.fromTinybars(100)) .setNodeAccountIds([AccountId.fromString("0.0.5")]) .freezeWith(client); const txByte = transaction.toBytes(); const signature = operatorKey.sign(txByte); transaction = Transaction.fromBytes(txByte); transaction.addSignature(operatorKey.publicKey, signature); const txResponse = await transaction.execute(client); const receipt = await txResponse.getReceipt(client); } main();