如何解决初始化向量IV-> toString('hex') -> 写入文件-> 从文件读取-> hex 到bin-> UndefinedUndefined 等NodeJS
我正在尝试将初始化向量存储为字符串十六进制,然后将其检索回二进制,但是当我将 结果打印到控制台时,它显示以下内容:
/// <summary>
/// Returns all projects
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesDefaultResponseType]
[HttpGet]
public async Task<IActionResult> Get(int? id)
{
return Ok(await Mediator.Send(new GetProjectsQuery { Id = id }));
}
为什么打印 undefined?我怎样才能达到预期的结果? 假设正确生成了 IV...
相关代码:
fIV: undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined; Passphrase: passrig
SignUp 函数中的相关片段,我正在写入 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');
}
解决方法
我创建了一个将 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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。