You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用dotenv在JavaScript中加密私钥遇TypeError问题排查与解决

解决ethers.js加密以太坊私钥时的TypeError问题

在使用JavaScript结合dotenv加密以太坊私钥时,触发错误:TypeError: Cannot read properties of undefined (reading 'toHexString'),同时鼠标悬停环境变量时显示string | undefined,即使encrypt.js和.env文件放在同一目录也无法解决。

问题代码及配置

encrypt.js

const ethers = require("ethers");
const fs = require("fs-extra");
require("dotenv").config();

async function main() {
  const wallet = new ethers.Wallet(process.env.RRIVATE_KEY);
  const encryptedJsonKey = await wallet.encrypt(
    process.env.PRIVATE_KEY_PASSWORD,
    process.env.PRIVATE_KEY
  );
  console.log(encryptedJsonKey);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

.env文件

PRIVATE_KEY=0x3ed74d4599fbc880e1f2dd094bf1dde078e808779f4f888d4b59a6d07bee99cb
RPC_URL=http://127.0.0.1:7545
PRIVATE_KEY_PASSWORD=password

问题原因及修复

错误根源是变量名拼写错误:代码中process.env.RRIVATE_KEY多写了一个字母R,正确的变量名应为process.env.PRIVATE_KEY(与.env文件中定义的变量名一致)。

由于拼写错误,process.env.RRIVATE_KEY的值为undefined,传入ethers.Wallet构造函数后无法初始化有效的钱包实例,后续调用encrypt方法时触发了toHexString的未定义属性读取错误。

修复后的encrypt.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);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

内容的提问来源于stack exchange,提问作者rocco zha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:00:54