开发者问题收集

未捕获的类型错误:无法读取未定义的属性(读取“utils”)

2023-02-16
2904

我正在尝试生成随机加密密钥,但是当我尝试运行我的应用程序时,浏览器控制台中会出现此错误 Uncaught TypeError: Cannot read properties of undefined (reading 'utils')

这是我的代码:

import secp from "ethereum-cryptography/secp256k1";
import { keccak256 } from "ethereum-cryptography/keccak";
import { toHex } from "ethereum-cryptography/utils";

const privateKey = secp.utils.randomPrivateKey();
console.log('Private key:', toHex(privateKey));

const publicKey = secp.getPublicKey(privateKey);
console.log('Public key:', toHex(publicKey));

const address = (keccak256(publicKey.slice(1)).slice(-20));
console.log('Ethereum public key:', toHex(address));

function GenerateKey() {
    return (
        <div>
            <p>Private key: {privateKey}</p>
            <p>Public key: {publicKey}</p>
            <p>Address: {address}</p>
        </div>
    )
}

export default GenerateKey;

请问我该如何修复此问题?

3个回答

尝试使用如下导入:

import {
  getPublicKey,
  utils,
} from 'ethereum-cryptography/secp256k1'

然后生成您的密钥:

const privateKey = utils.randomPrivateKey()

const publicKey = getPublicKey(privateKey)

您会收到错误,因为 ethereum-cryptography/secp256k1 路径没有默认导出。

另一种方法是使用 * as 构造:

import * as secp from 'ethereum-cryptography/secp256k1'

const privateKey = secp.utils.randomPrivateKey()

const publicKey = secp.getPublicKey(privateKey)
Pavel Sturov
2023-02-16

尝试将 secp 导入为 secp256k1 ,如下所示:

将第 1 行更改为:

import { secp256k1 } from 'ethereum-cryptography/secp256k1';

将第 5 行更改为:

const privateKey = secp256k1.utils.randomPrivateKey();

将第 8 行更改为:

const publicKey = secp256k1.getPublicKey(privateKey);

这是因为对 secp256k1 模块进行了更新。之前使用的是 noble-secp256k1 1.7 ,现在使用的是更安全的 noble-curve 。请参阅 curves README 中的升级部分

希望这对您有所帮助。

Edna
2023-06-13

尝试用 const { secp256k1 } = require("ethereum-cryptography/secp256k1.js");

替换 import secp from "ethereum-cryptography/secp256k1";

并使用 secp256k1.utils 代替 secp.utils ...

user22392433
2023-08-15