5.区块链系列之私钥管理
本文讲解如何对私钥加密处理以及部署后需注意的事项
1.新建encryptKey.js
const ethers = require("ethers");
const fs = require("fs-extra");
require("dotenv").config();
async function main() {
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY);
const encryptedJsonKey = await wallet.encrypt(
process.env.PRIVATE_KEY_PASSWORD,
process.env.PRIVATE_KEY
);
console.log(encryptedJsonKey);
fs.writeFileSync("./.encryptedKey.json", encryptedJsonKey);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
目前我们的.env文件配置为
PRIVATE_KEY=36b785b98b0567f1e6cdfe4f67e884d8d3fb24ba0dbac0776f935d558f39e165
RPC_URL=http://127.0.0.1:7545
PRIVATE_KEY_PASSWORD=shenjian.online
控制台执行生成.encryptedKey.json文件
(base) PS D:\blockchain\ehthers-simple-storage-fcc> node encryptKey.js
现在我们删除.env中的PRIVATE_KEY=36b785b98b0567f1e6cdfe4f67e884d8d3fb24ba0dbac0776f935d558f39e165
2. 修改deploy.js私钥部分
现在我们将上节介绍的deploy.js文件中注释私钥部分放开
async function main() {
let provider = new ethers.providers.JsonRpcProvider(process.env.RPC_URL);
// 私钥不加密方式,开发
//let wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
// 生产环境私钥一定要加密,并且history历史命令记录也要清空,否则后果自负!!!!!!!!
const encryptedJson = fs.readFileSync("./.encryptedKey.json", "utf8");
let wallet = new ethers.Wallet.fromEncryptedJsonSync(
encryptedJson,
process.env.PRIVATE_KEY_PASSWORD
);
wallet = wallet.connect(provider);
......
}
再次运行部署,同样成功
(base) PS D:\blockchain\ehthers-simple-storage-fcc> node deploy.js
Deploying, please wait...
Contract deployed to 0xe52A9CFCCAd1cDF934614D0Cd93BB7Fa9650ae64
Current Favorite Number: 0
Updating favorite number...
New Favorite Number: 7
3. linux下进一步安全
.env文件中我们去掉PRIVATE_KEY_PASSWORD=shenjian.online,
然后运行[linux下]
PRIVATE_KEY_PASSWORD=shenjian.online node deploy.js
history -c