SuperAPI AI 工具集

nodejs-keccak256-v1

编程与开发

查看项目

更新于 10-27 16:22

技能介绍

用途

该技能用于在 JavaScript 和 TypeScript 项目中避免以太坊哈希相关的错误。核心问题是:以太坊使用 Keccak-256,而不是 Node 的 crypto.createHash('sha3-256') 所暴露的 NIST 标准化 SHA3 变体。两者对相同输入产生不同输出,且 Node 不会给出任何警告,因此会静默破坏函数选择器、事件主题、签名、EIP-712、Merkle 证明、存储槽和地址派生等。

适用范围限定为以太坊哈希:函数选择器、事件主题、EIP-712、Merkle 证明、存储槽、地址派生。

主要能力

  • 识别并避免在以太坊场景中误用 Node 的 sha3-256。
  • 提供 ethers v6、viem、web3.js 三种库的 Keccak-256 使用示例。
  • 覆盖常见模式:函数选择器、事件主题(typeHash)、映射存储槽计算、由公钥派生地址。
  • 提供审计代码库的 grep 命令,用于查找误用 createHash('sha3-256') 的位置以及 keccak256 的使用情况。

使用方式

明确要求:不得改写用于 JWT 令牌、OAuth PKCE、API 密钥或其他应用密钥的 Node createHash('sha256'),因为 Keccak 不是 SHA-256。

优先选择:当 viem 已是项目依赖时,优先使用 viem 的 keccak256;仅当应用已依赖 ethers 时才使用 ethers。

示例(ethers v6):

import { keccak256, toUtf8Bytes, solidityPackedKeccak256, id } from 'ethers';

const hash = keccak256(new Uint8Array([0x01, 0x02]));
const hash2 = keccak256(toUtf8Bytes('hello'));
const topic = id('Transfer(address,address,uint256)');
const packed = solidityPackedKeccak256(
  ['address', 'uint256'],
  ['0x742d35Cc6634C0532925a3b8D4C9B569890FaC1c', 100n],
);

示例(viem):

import { keccak256, toBytes } from 'viem';

const hash = keccak256(toBytes('hello'));

示例(web3.js):

const hash = web3.utils.keccak256('hello');
const packed = web3.utils.soliditySha3(
  { type: 'address', value: '0x742d35Cc6634C0532925a3b8D4C9B569890FaC1c' },
  { type: 'uint256', value: '100' },
);

常见模式:

import { id, keccak256, AbiCoder } from 'ethers';

const selector = id('transfer(address,uint256)').slice(0, 10);
const typeHash = keccak256(toUtf8Bytes('Transfer(address from,address to,uint256 value)'));

function getMappingSlot(key: string, mappingSlot: number): string {
  return keccak256(
    AbiCoder.defaultAbiCoder().encode(['address', 'uint256'], [key, mappingSlot]),
  );
}

由公钥派生地址:

import { keccak256 } from 'ethers';

function pubkeyToAddress(pubkeyBytes: Uint8Array): string {
  const hash = keccak256(pubkeyBytes.slice(1));
  return '0x' + hash.slice(-40);
}

审计代码库:

grep -rn "createHash.*sha3" --include="*.ts" --include="*.js" --exclude-dir=node_modules .
grep -rn "keccak256" --include="*.ts" --include="*.js" . | grep -v node_modules

适用场景

  • 计算以太坊函数选择器或事件主题。
  • 在 JS/TS 中构建 EIP-712、签名、Merkle 或存储槽辅助函数。
  • 审查任何直接使用 Node crypto 对以太坊数据进行哈希的代码。

限制

  • 仅适用于以太坊哈希场景,不适用于 JWT、OAuth PKCE、API 密钥等应用密钥的 SHA-256 哈希。
  • 非 EVM 地址验证应使用 solana-v1(资料中提及的互补技能)。
  • 规则:在以太坊上下文中,绝不使用 crypto.createHash('sha3-256'),应使用 ethers、viem、web3 或其他明确的 Keccak 实现提供的 Keccak 感知辅助函数。

交互

与 viem-v2 互补,用于 EVM 客户端和 keccak256 辅助函数。