如何使用Hedera SDK的PrivateKey与PublicKey实现数据加解密?
与Hedera SDK密钥兼容的公钥加密/解密方案
方案1:使用官方@hashgraph/crypto包(优先推荐)
Hedera官方维护的@hashgraph/crypto包原生支持与SDK密钥的兼容,能处理ED25519与X25519密钥的转换(因为ED25519默认用于签名,加密需要用X25519做密钥交换)。
步骤:
- 安装依赖:
npm install @hashgraph/crypto
- 代码示例:
const { PrivateKey } = require("@hashgraph/sdk"); const { encrypt, decrypt, ed25519PrivateKeyToX25519, ed25519PublicKeyToX25519 } = require("@hashgraph/crypto"); // 从Hedera SDK获取已有的密钥(示例中生成新密钥演示) const hederaPrivateKey = PrivateKey.generateED25519(); const hederaPublicKey = hederaPrivateKey.publicKey; // 转换ED25519密钥到X25519格式(用于加密操作) const x25519PrivateKey = ed25519PrivateKeyToX25519(hederaPrivateKey); const x25519PublicKey = ed25519PublicKeyToX25519(hederaPublicKey); // 待加密的明文数据 const plaintext = "你的敏感数据内容"; const plaintextBuffer = Buffer.from(plaintext, "utf8"); // 用对方的X25519公钥加密数据 const encryptedData = encrypt(plaintextBuffer, x25519PublicKey); // 用自己的X25519私钥解密数据 const decryptedBuffer = decrypt(encryptedData, x25519PrivateKey); const decryptedText = decryptedBuffer.toString("utf8"); console.log("解密结果:", decryptedText);
方案2:使用Node.js原生crypto模块
如果偏好原生模块,可手动将Hedera密钥转换为crypto支持的格式,适合ECDSA类型的密钥(如secp256r1/secp256k1),ED25519密钥不建议用此方案(原生crypto对其加密支持有限)。
代码示例:
const { PrivateKey } = require("@hashgraph/sdk"); const crypto = require("crypto"); // 生成Hedera ECDSA secp256r1密钥(或使用已有的账户密钥) const hederaPrivateKey = PrivateKey.generateECDSA(); const hederaPublicKey = hederaPrivateKey.publicKey; // 转换Hedera密钥为Node.js crypto兼容格式 // 私钥转PKCS#8 DER格式 const privateKey = crypto.createPrivateKey({ key: hederaPrivateKey.toBytes(), format: "der", type: "pkcs8" }); // 公钥转SPKI DER格式 const publicKey = crypto.createPublicKey({ key: hederaPublicKey.toBytes(), format: "der", type: "spki" }); // 生成AES密钥(非对称加密适合加密小数据,因此用对称加密处理明文,再加密对称密钥) const aesKey = crypto.randomBytes(32); const iv = crypto.randomBytes(16); // 用AES加密明文 const cipher = crypto.createCipheriv("aes-256-cbc", aesKey, iv); let encryptedData = cipher.update("你的敏感数据内容", "utf8", "base64"); encryptedData += cipher.final("base64"); // 用公钥加密AES密钥 const encryptedAesKey = crypto.publicEncrypt(publicKey, aesKey).toString("base64"); // 解密流程:先解AES密钥,再解明文 const decryptedAesKey = crypto.privateDecrypt(privateKey, Buffer.from(encryptedAesKey, "base64")); const decipher = crypto.createDecipheriv("aes-256-cbc", decryptedAesKey, iv); let decryptedText = decipher.update(encryptedData, "base64", "utf8"); decryptedText += decipher.final("utf8"); console.log("解密结果:", decryptedText);
关键注意事项
- ED25519密钥限制:Hedera默认的ED25519密钥仅用于签名,不能直接用于非对称加密,必须通过
@hashgraph/crypto转换为X25519格式才能进行加密操作。 - 加密效率:非对称加密直接加密大数据性能极低,建议采用「对称加密明文+非对称加密对称密钥」的混合方案(方案2已实现此逻辑)。
- 兼容性:
@hashgraph/crypto由Hedera官方维护,能确保与SDK密钥的完全兼容,是首选方案。
内容的提问来源于stack exchange,提问作者Abi
相关产品推荐
相关产品推荐

