yxchain-encryption-nodejs
是一个功能强大的区块链加密工具库,提供了密钥对管理、数字签名和密钥存储等核心功能。
npm install yxchain-encryption-nodejs --save
该库提供三个主要模块:
- KeyPair: 密钥对管理,用于生成和管理公私钥对
- Signature: 数字签名功能,用于消息签名和验证
- Keystore: 安全的密钥存储方案,支持加密存储私钥
const { keypair } = require('yxchain-encryption-nodejs');
// 方式1:创建实例
const kp = new keypair();
const encPrivateKey = kp.getEncPrivateKey();
const encPublicKey = kp.getEncPublicKey();
const address = kp.getAddress();
// 方式2:使用静态方法
const { encPrivateKey, encPublicKey, address } = keypair.getKeyPair();
const encPublicKey = keypair.getEncPublicKey(encPrivateKey);
const address = keypair.getAddress(encPublicKey);
// 验证私钥格式
const isValidPrivateKey = keypair.checkEncPrivateKey(encPrivateKey);
// 验证公钥格式
const isValidPublicKey = keypair.checkEncPublicKey(encPublicKey);
// 验证地址格式
const isValidAddress = keypair.checkAddress(address);
const { signature } = require('yxchain-encryption-nodejs');
const sign = signature.sign(message, encPrivateKey);
const isValid = signature.verify(message, sign, encPublicKey);
const { keystore } = require('yxchain-encryption-nodejs');
keystore.encrypt(encPrivateKey, password, function(encryptedData) {
// encryptedData 包含加密后的私钥信息
// {
// cypher_text: "加密后的私钥",
// aesctr_iv: "初始化向量",
// scrypt_params: {
// n: 16384,
// p: 1,
// r: 8,
// salt: "加密盐值"
// },
// version: 2
// }
});
keystore.decrypt(encryptedData, password, function(decryptedPrivateKey) {
// decryptedPrivateKey 是解密后的私钥
});
const encryption = require('yxchain-encryption-nodejs');
const { keypair, signature, keystore } = encryption;
// 1. 创建新的密钥对
const kp = new keypair();
const encPrivateKey = kp.getEncPrivateKey();
const encPublicKey = kp.getEncPublicKey();
const address = kp.getAddress();
console.log('密钥对信息:');
console.log(`私钥: ${encPrivateKey}`);
console.log(`公钥: ${encPublicKey}`);
console.log(`地址: ${address}`);
// 2. 签名消息
const message = 'Hello YXChain';
const sign = signature.sign(message, encPrivateKey);
console.log(`消息签名: ${sign}`);
// 3. 验证签名
const isValid = signature.verify(message, sign, encPublicKey);
console.log(`签名验证结果: ${isValid}`);
// 4. 加密存储私钥
keystore.encrypt(encPrivateKey, 'your-password', function(encryptedData) {
console.log('加密后的私钥数据:', encryptedData);
// 5. 解密私钥
keystore.decrypt(encryptedData, 'your-password', function(decryptedPrivateKey) {
console.log(`解密后的私钥: ${decryptedPrivateKey}`);
console.log(`解密的私钥是否与原私钥相同: ${decryptedPrivateKey === encPrivateKey}`);
});
});
- 请妥善保管私钥,不要泄露给他人
- 建议使用 Keystore 模块加密存储私钥
- 使用强密码保护您的 Keystore 文件
- 定期备份您的密钥信息
npm test