javascript - 初始化向量 (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'));
解决方案
我创建了一个将 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()
推荐阅读
- javascript - 无法提交 Google 表单字段,输入已填写
- c# - 重构多个自依赖的等待调用
- bazel - 如何从本地文件模拟 http_archive
- java - Mapstruct双向映射抛出内存错误
- python - 我正在尝试用python制作一个基本的计算器。我包括一个函数索引
- java - Allure Cucumber Maven 报告问题
- mongodb - MongoDB 不能用空格引用字段
- android - Android Clean Architecture:当模型引用两个房间表时缓存映射
- oracle - Oracle,子查询上的复杂条件
- flutter - Flutter:在构建方法之外的 Widget 实例变量中存储依赖项可以吗?