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

使用crypto加密密码时遇crypto.createHash is not a function错误求助

前端环境下crypto模块加密问题的解决方法

方案一:改用前端专用加密库(推荐)

Node.js的crypto模块为后端设计,浏览器环境下使用会存在兼容性问题。直接改用crypto-js这类前端友好的加密库,无需配置polyfill:

  1. 安装依赖:
npm install crypto-js
# 或 yarn add crypto-js
  1. 替换原有加密代码:
import CryptoJS from 'crypto-js';

export const encrypt = (text: string) => {
    const algorithm = 'AES';
    // 生成32位密钥(对应aes256)
    const key = CryptoJS.SHA256(String(reactApp))
        .toString(CryptoJS.enc.Base64)
        .substr(0, 32);
    
    // AES加密示例(根据你的实际加密逻辑调整)
    const encrypted = CryptoJS.AES.encrypt(text, key).toString();
    return encrypted;
};

方案二:修复crypto-browserify的配置问题

如果坚持使用crypto-browserify,需要补全所有缺失的Node.js核心模块polyfill,并正确配置webpack:

  1. 安装所有依赖包:
npm install crypto-browserify stream-browserify buffer assert stream-http https-browserify os-browserify url process
# 或 yarn add 上述包
  1. 更新webpack配置(webpack.config.ts):
const path = require('path');
const webpack = require('webpack');

module.exports = {
    resolve: {
        fallback: {
            crypto: require.resolve('crypto-browserify'),
            stream: require.resolve('stream-browserify'),
            buffer: require.resolve('buffer'),
            assert: require.resolve('assert'),
            http: require.resolve('stream-http'),
            https: require.resolve('https-browserify'),
            os: require.resolve('os-browserify'),
            url: require.resolve('url'),
        },
        extensions: ['.ts', '.tsx', '.js'],
    },
    plugins: [
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer'],
        }),
    ],
};
  1. 若使用Create React App(CRA),需借助react-app-rewired修改配置:
    • 安装依赖:
      npm install react-app-rewired customize-cra --save-dev
      
    • 根目录创建config-overrides.js:
      const { override, addWebpackPlugin, addWebpackResolve } = require('customize-cra');
      const webpack = require('webpack');
      
      module.exports = override(
          addWebpackResolve({
              fallback: {
                  crypto: require.resolve('crypto-browserify'),
                  stream: require.resolve('stream-browserify'),
                  buffer: require.resolve('buffer'),
                  assert: require.resolve('assert'),
              },
          }),
          addWebpackPlugin(
              new webpack.ProvidePlugin({
                  process: 'process/browser',
                  Buffer: ['buffer', 'Buffer'],
              })
          )
      );
      
    • 修改package.json启动命令:
      "scripts": {
          "start": "react-app-rewired start",
          "build": "react-app-rewired build",
          "test": "react-app-rewired test"
      }
      

方案三:使用浏览器原生Web Crypto API

浏览器提供了原生的Web Crypto API,异步设计且无需额外依赖:

export const encrypt = async (text: string) => {
    // 生成密钥
    const encoder = new TextEncoder();
    const hashBuffer = await crypto.subtle.digest('SHA-256', encoder.encode(String(reactApp)));
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashBase64 = btoa(String.fromCharCode(...hashArray));
    const key = hashBase64.substr(0, 32);

    // Web Crypto AES加密示例
    const keyBuffer = encoder.encode(key);
    const cryptoKey = await crypto.subtle.importKey(
        'raw',
        keyBuffer,
        { name: 'AES-CBC' },
        false,
        ['encrypt']
    );
    const iv = crypto.getRandomValues(new Uint8Array(16));
    const encryptedBuffer = await crypto.subtle.encrypt(
        { name: 'AES-CBC', iv: iv },
        cryptoKey,
        encoder.encode(text)
    );

    // 拼接iv和加密结果返回(解密时需拆分)
    const encryptedArray = new Uint8Array(iv.length + encryptedBuffer.byteLength);
    encryptedArray.set(iv, 0);
    encryptedArray.set(new Uint8Array(encryptedBuffer), iv.length);
    return btoa(String.fromCharCode(...encryptedArray));
};

内容的提问来源于stack exchange,提问作者Virat Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:16:33