uni-app APP下使用nodejs crypto模块问题

uni-app APP下使用nodejs crypto模块问题

开发环境 版本号 项目创建方式
Mac 14.2 HBuilderX

产品分类:uniapp/App

PC开发环境操作系统:Mac

HBuilderX类型:正式

HBuilderX版本号:3.99

手机系统:iOS

手机系统版本号:iOS 17

手机厂商:苹果

手机机型:iphone 12 pro max

页面类型:vue

vue版本:vue3

打包方式:云端

示例代码:

const { KeyObject, createSecretKey, createPrivateKey } = require('crypto');
console.log("createSecretKey: " + createSecretKey);
console.log(KeyObject);

操作步骤:

const { KeyObject, createSecretKey, createPrivateKey } = require('crypto');
console.log("createSecretKey: " + createSecretKey);
console.log(KeyObject);

预期结果:

打印出function函数

实际结果:

createSecretKey: undefined
undefined

bug描述:

使用内置的crypto模块,没有相关的属性


更多关于uni-app APP下使用nodejs crypto模块问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

4 回复

现在dcloud是没人管uniapp了吗,发过好几个帖子,没一个人回

更多关于uni-app APP下使用nodejs crypto模块问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uniapp没有内置crypto,这个是vite的问题,你这个crypto模块是不对外暴露的,你得自己安装crypto 可以参考我下面的代码 npm install crypto-js

<script> import CrypotJS from 'crypto-js' export default { onReady: function(e) { let passwordSha256 = CrypotJS.SHA256(12313 + 3213123).toString(); console.log("passwordSha256: " + passwordSha256); } } </script>

谢谢,这个问题解决了,websocket的那个问题https://ask.dcloud.net.cn/question/184968可以帮我看看吗

在 uni-app 中使用 Node.js 的 crypto 模块可能会遇到一些问题,因为 uni-app 是基于前端技术栈(如 Vue.js)的跨平台开发框架,而 crypto 是 Node.js 的核心模块,主要用于服务器端环境。在 uni-app 的 APP 端(如 H5、小程序、App)中,直接使用 Node.js 的 crypto 模块是不可行的,因为这些平台并不支持 Node.js 环境。

解决方案

  1. 使用 Web Crypto API

    • 在浏览器环境(如 H5)中,可以使用 Web Crypto API 来替代 Node.js 的 crypto 模块。Web Crypto API 是浏览器原生支持的加密 API,提供了类似的功能。
    • 示例:
      async function generateHash(message) {
        const encoder = new TextEncoder();
        const data = encoder.encode(message);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
        return hashHex;
      }
      
      generateHash('Hello, world!').then(hash => console.log(hash));
      
  2. 使用第三方加密库

    • 如果你需要在所有平台(包括小程序和 App)中实现加密功能,可以使用一些跨平台的 JavaScript 加密库,如 crypto-jsjs-sha256
    • 示例(使用 crypto-js):
      import CryptoJS from 'crypto-js';
      
      const message = 'Hello, world!';
      const hash = CryptoJS.SHA256(message).toString(CryptoJS.enc.Hex);
      console.log(hash);
      
  3. 在云函数中使用 Node.js crypto 模块

    • 如果你需要在服务器端进行加密操作,可以将加密逻辑放在云函数中,然后在 uni-app 中调用云函数。云函数通常运行在 Node.js 环境中,可以直接使用 crypto 模块。
    • 示例(云函数):
      const crypto = require('crypto');
      
      exports.main = async (event, context) => {
        const hash = crypto.createHash('sha256').update(event.message).digest('hex');
        return { hash };
      };
      
    • 在 uni-app 中调用云函数:
      uniCloud.callFunction({
        name: 'yourCloudFunction',
        data: { message: 'Hello, world!' }
      }).then(res => {
        console.log(res.result.hash);
      });
回到顶部