Error message "error:0308010C:digital envelope routines::unsupported"

Error message “error:0308010C:digital envelope routines::unsupported”

技术背景

在 Node.js v17 中,开发者修复了 SSL 提供程序中的一个安全漏洞,但这个修复是一个重大变更,同时 NPM 中的 SSL 包也有类似的重大变更。当在 Node.js v17 或更高版本中尝试使用 SSL ,而 package.json 中的 SSL 包没有升级时,就会出现 "error:0308010C:digital envelope routines::unsupported" 错误。

实现步骤

1. 重新安装依赖

删除 node_modules 文件夹,然后重新运行 npm install。如果依赖项需要根据你安装的 Node 版本进行编译,此操作可能会立即解决问题。

1
2
rm -rf node_modules
npm install

2. 更新依赖

查找依赖项对应 Node 18 成为 LTS 版本之后的版本,并将依赖项升级到该版本。这是解决问题的正确方法,因为旧版本的依赖项可能会使项目面临攻击风险。

1
npm update

3. 降级到 Node.js v16

可以使用官方 Node 安装程序或 nvm(Windows 使用 nvm-windows)将 Node 降级到 v16 版本。不过,这只是权宜之计,因为运行不安全且可能存在漏洞的代码并非长久之计。

1
2
3
# 使用 nvm 安装 Node.js v16
nvm install 16
nvm use 16

4. 让 Node 使用旧版 OpenSSL 提供程序

  • Unix-like 系统(Linux、macOS、Git bash 等)
1
export NODE_OPTIONS=--openssl-legacy-provider
  • Windows 命令提示符
1
set NODE_OPTIONS=--openssl-legacy-provider
  • PowerShell
1
$env:NODE_OPTIONS = "--openssl-legacy-provider"

5. 针对 Webpack 的解决方案

在 Webpack 配置中设置以下内容:

  • Webpack v5:设置 output.hashFunction = 'xxhash64'
  • Webpack v4:根据系统上 Node.js 支持的哈希算法进行设置,例如 output.hashFunction = 'sha512'output.hashFunction = 'sha256'

6. 针对不同框架的解决方案

  • React:将 package.json 中的启动脚本修改为:
1
"start": "react-scripts --openssl-legacy-provider start"

也可以将 react-scripts 升级到 5.0.0 或更高版本:

1
npm i react-scripts@latest
  • Vue.js
    • 启用旧版 OpenSSL 提供程序,在不同系统上的设置方法与上述一致。
    • package.json 中重新配置 npm run serve 脚本:
1
2
3
"scripts": {
"serve": "vue-cli-service serve --openssl-legacy-provider"
}
  • Angular:将 package.json 中的 npm start 脚本修改为:
1
"start": "set NODE_OPTIONS=--openssl-legacy-provider && ng serve -o"

核心代码

针对 Vue.js 拦截 createHash() 调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const crypto = require('crypto');

/**
* The MD4 algorithm is not available anymore in Node.js 17+ (because of library SSL 3).
* In that case, silently replace MD4 by the MD5 algorithm.
*/
try {
crypto.createHash('md4');
} catch (e) {
console.warn('Crypto "MD4" is not supported anymore by this Node.js version');
const origCreateHash = crypto.createHash;
crypto.createHash = (alg, opts) => {
return origCreateHash(alg === 'md4' ? 'md5' : alg, opts);
};
}

最佳实践

  • 始终使用最新版本的 Node.js 和经过安全更新的包,以确保项目的安全性。
  • 在更新依赖项之前,先在开发环境中进行测试,以避免引入兼容性问题。
  • 尽量避免使用降级 Node.js 版本或使用旧版 OpenSSL 提供程序的方法,因为这会使项目面临安全风险。

常见问题

1. npm audit fix --force 导致构建失败

对于复杂的构建,npm audit fix --force 可能会引入重大的安全修复,从而可能破坏构建。在这种情况下,可以手动检查和更新依赖项。

2. --openssl-legacy-provider 在旧版本 Node.js 中不支持

如果需要兼容旧版本的 Node.js,可以考虑使用其他解决方案,如更新 Webpack 的哈希算法。


Error message "error:0308010C:digital envelope routines::unsupported"
https://119291.xyz/posts/2025-05-14.error-message-digital-envelope-routines-unsupported/
作者
ww
发布于
2025年5月14日
许可协议