我正在尝试使用
crypto.subtle.digest()
作为我正在处理的文件上传项目的校验和函数的一部分,但由于某种原因,我不断收到以下错误:
upload-form.tsx:129 Uncaught TypeError: Cannot read properties of undefined (reading 'digest')
这表明
crypto.subtle
未定义。我知道 crypto.subtle
仅在安全上下文 (HTTPS) 中可用,但我尝试在 http://localhost:3000
中使用它,我读到它也被认为是安全上下文。我已经在 Chrome 和 Firefox 中尝试过,并且在两者中都得到相同的未定义错误。
我正在使用
NextJS 14.1.0
和 Node.js v20.11.0
我在
http://localhost:3000
、Chrome v121.0.6167.160
和Firefox ESR v115.3.0esr
上进行了测试
我在客户端组件中使用
import * as crypto from "crypto"
(我在顶部有 "use client";
)
这是我正在使用的校验和函数,是我从这个 Youtube 教程 中获得的,但仅简要展示了它。
评论来自ChatGPT,他们也提出了基本相同的功能。
//upload-form.tsx
"use client";
... //imports
import * as crypto from "crypto";
... //some code
const computeSHA256 = async (file: File) => {
// Convert file to an array buffer
const buffer = await file.arrayBuffer();
// Calculate SHA-256 hash
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
// Convert hashBuffer to hexadecimal representation
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
return hashHex;
};
... //rest of file
使用
crypto.webcrypto.subtle.digest()
,我收到错误:
upload-form.tsx:133 Uncaught TypeError: Cannot read properties of undefined (reading 'subtle')
这表明
crypto.webcrypto
未定义。
如果我使用
window.crypto.subtle.digest()
代替,那么该函数运行得非常好,但我想知道这是否是正确的方法。
我用
console.log(crypto)
查看它有什么属性,webcrypto
或subtle
都不在那里。
在 Chrome 的控制台中直接打印
window.crypto
显示它确实有 subtle
好吧,在查看了 Youtube 教程所有者提供的 github repo 后,我注意到他从未在文件顶部实际使用过
import crypto from 'crypto'
。我想知道他如何能够在不导入加密的情况下使用加密,但我想事实证明,如果不导入,javascript/react/nextjs (??) 会将 crypto
变量默认为 Web Crypto API crypto
。
我不知道这是一件事。
如果我的理解是正确的,那么,这与仅使用
window.crypto
是一样的,这就是我最初用来让函数正常工作的方法。