首页 > 解决方案 > 初始化向量 (IV) -> toString('hex') -> 写入文件 -> 从文件读取 -> 十六进制到 bin-> UndefinedUndefined 等 NodeJS

问题描述

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

fIV: undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined; Passphrase: passrig

为什么打印未定义?我怎样才能达到预期的结果?假设 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'));

标签: javascriptnode.jsencryptionbinaryhex

解决方案


我创建了一个将 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()

推荐阅读