node.js 加密 pbkdf2 return 未定义

node.js crypto pbkdf2 return undefined

export const upgradeBase64crypto = (password) => {
    crypto.randomBytes(64, (err, buf) => {
        const salt = buf.toString("base64");
      
        crypto.pbkdf2(password, salt, 100, 64, "sha512", (err, key) => {
            return key.toString("base64");
        });
    });
};

import { upgradeBase64crypto } from "../../../utils/pwCrypto";

export default {
    Mutation: {
        signUpUser: async (_, args, { request, query }) => {
            try {
                const param = args.param;
                let pw = upgradeBase64crypto(param.pw);
              
                console.log(pw);
            } 
          catch (err) {}
        },
    },
};

当运行console.log(key.toString('base64'))upgradeBase64crypto时,正常加密的字符串出现在日志中。然而,运行return key.toString('base64')returnsundefined。有什么问题吗?

您没有从 upgradeBase64crypto 函数返回任何值。尝试:

export const upgradeBase64crypto = (password) => {
    let passwordHash;

    crypto.randomBytes(64, (err, buf) => {
        const salt = buf.toString('base64');
        
        passwordHash = crypto.pbkdf2(password, salt, 100, 64, 'sha512', (err, key) => {
            return key.toString('base64');
        });
    });

    return passwordHash;
}

编辑:

抱歉,错过了回调包装。这将解决您的问题:

const upgradeBase64crypto = (password) => {
    return new Promise((resolve, reject) => {        
        crypto.randomBytes(64, (err, buf) => {
            const salt = buf.toString('base64');

            crypto.pbkdf2(password, salt, 100, 64, 'sha512', (err, key) => {
                resolve(key.toString('base64'));
            });
        })
    });
}

之前您试图在回调有机会设置它之前访问该值,因为您使用的是 crypto 方法的 async 版本。现在它 returns 一个承诺。您需要 .thenawait 您的 signUpUser 方法中的操作:

signUpUser: async (_, args, { request, query }) => {
    try {
        const param = args.param;
        let pw = await upgradeBase64crypto(param.pw);

        console.log(pw);
    }
    catch(error) { }
}