初始化向量 (IV) -> toString('hex') -> 写入文件 -> 从文件读取 -> hex 到 bin -> UndefinedUndefined 等等 NodeJS

Initialization Vector (IV) -> toString('hex') -> write to file -> read from file-> hex to bin-> UndefinedUndefined Etc. NodeJS

我正在尝试将初始化向量存储为十六进制字符串,然后将其检索回二进制,但是当我将 结果打印到控制台时,它显示以下内容:

fIV: undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined; Passphrase: passrig

为什么打印的是undefined?我怎样才能达到预期的结果? 假设 IV 生成正确...

相关代码:

SignIn(pass)
{
    console.log(`fIV: ${h2b(fIV)}; Passphrase: ${pass}`);
    const key = crypto.scryptSync(pass, 'baethrowssalt', 32);
    var decipher = crypto.createDecipheriv(algorithm, key, h2b(fIV)); 
    var decrypted = decipher.update(secret, 'hex', 'binary') + decipher.final('binary');

    if(encrypted !== crypto.createCipheriv(algorithm, key).update(decrypted,'binary','hex') + cipher.final('hex'))
    {
        return alert(`access denied: encrypted:${encrypted}, secret:${secret}`);
    };
    return Buffer.from(decrypted, 'hex');

}

h2b(hex){
    return (parseInt(hex, 16).toString(2)).padStart(8, '0');
}

SignUp 函数中的相关片段,我正在写入 IV 文件:

   fs.writeFileSync(fileIV, iv.toString('hex'));

我创建了一个将 IV 写入文件然后再读回的示例。我们对文件数据使用十六进制编码。如果您不需要观察它,将二进制形式的 IV 写入文件可能会更容易,我已经包含了这两个示例。

const crypto = require("crypto");
const fs = require("fs");

// Write the IV to file in hex format and read it back again...
function testIVFileHex() {
    const IV = crypto.randomBytes(32);
    console.log("testIVFileHex: IV (write to file):  " + IV.toString("hex"));
    fs.writeFileSync("iv.txt", IV.toString("hex"));

    const IVFromFile = Buffer.from(fs.readFileSync("iv.txt", "utf-8"), "hex");
    console.log("testIVFileHex: IV (read from file): " + IVFromFile.toString("hex"));
}

// Write the IV to file in binary format and read it back again...
function testIVFileBinary() {
    const IV = crypto.randomBytes(32);
    console.log("testIVFileBinary: IV (write to file):  " + IV.toString("hex"));
    fs.writeFileSync("iv.dat", IV);

    const IVFromFile = fs.readFileSync("iv.dat");
    console.log("testIVFileBinary: IV (read from file): " + IVFromFile.toString("hex"));
}

// On could use either function
testIVFileHex()
testIVFileBinary()