在javascript中生成哈希和盐[关闭]

问题描述 投票:0回答:1

我想在我的系统中实现盐哈希密码机制。我正在尝试导入或使用 Node.js (加密),但无法使其工作。我得到:需求中未捕获的引用错误。 预先感谢。

这是整个 javascript 代码,第一行是我尝试使用 Node.js 的地方。

let crypto;
try {
  crypto = require('node:crypto');
} catch (err) {
  console.error('crypto support is disabled!');
} 

function checkName(){
    var name= document.signUp.name.value.trim();

    for (let i = 0; i < name.length; i++){
        var ascii = name.charCodeAt(i); //UTF-16
        if ((ascii < 65 || ascii > 122) && (ascii!=32) && (ascii!=209 && ascii!=241) && (ascii!=225 && ascii!=193) && (ascii!=201 && ascii!=233) && (ascii!=205 && ascii!=237) && (ascii!=211 && ascii!=243) && (ascii!=218 && ascii!=250)){
            //209: Ñ, 241: ñ, y vocales con tílde
            return false;
        }
        
    }
    return true;
}

...

async function register(event){
    event.preventDefault();
    var crypto = require('crypto');
    //if all the checks are true, submit the form via POST fetch to /api/signup_register.php
    try {
        if (!checkName() || !checkSurname() || !checkDNI() || !checkTel() || !checkDate()) {
            return;
        }
    } catch (error) {
        alert("Algo ha ido mal")
        console.log(error);
        return;
    }

    res = await fetch('/api/signup_register.php', {
        method: 'POST',
        body: new FormData(document.getElementById('signUpForm'))
    })
    res = await res.text();
    console.log(res)
    if (res != 'Usuario registrado correctamente') {
        alert(res);
    }else{
        alert(res);
        window.location.reload()
    }
}

...

// EventListener de los dos botones disponibles en la página, para evitar el uso de onClicked en HTML.
document.addEventListener('DOMContentLoaded', (event) => {
    document.getElementById("SignUpButton").addEventListener("click", register);
    document.getElementById("LogInButton").addEventListener("click", login);
})

javascript node.js cryptojs
1个回答
0
投票

如果

require
抛出参考错误,则:

它是一个浏览器

没有使用 Node.js(在这种情况下,您可能尝试通过

<script>
元素在 Web 浏览器中运行代码)。

您在代码末尾隐藏了

document.addEventListener
的事实很好地表明了情况就是如此。

在浏览器中,您可以通过 global crypto

 访问 
Crypto API

if (typeof crypto !== "object") {
  console.error('crypto support is disabled!');
} 

我需要获取用户的用户名和密码,并用盐+哈希存储其密码

不要尝试推出自己的加密货币

您正在使用

fetch('/api/signup_register.php'
向 PHP 程序发出 Ajax 请求。要加密传输到服务器的数据使用 HTTPS。要对密码加盐,请使用 PHP 的
password_hash
函数

它是一个 ECMAScript 模块

Node.js 支持 ECMAScript 模块和 CommonJS 模块。

require
是 CommonJS 模块系统的一部分,在 ECMAScript 模块中不可用。

您可以:

使用
import
代替

import crypto from 'node:crypto';

使用 CommonJS 模块

  • 将文件重命名为具有
    .cjs
    文件扩展名
  • 确保文件具有
    .js
    文件扩展名 并且 您的
    package.json
    包括
    "type": "module"
© www.soinside.com 2019 - 2024. All rights reserved.