【问题标题】:How to store byte array into local file in JavaScript?如何在 JavaScript 中将字节数组存储到本地文件中?
【发布时间】:2020-02-24 10:23:04
【问题描述】:

我正在使用 openssl 证书。 所以我想要实现的是从我的 API 下载证书,它返回字节数组。例如:

0�
g0�
'   *�H��
��
�
0�

我尝试将这些写入文件,并使用其他函数读取并转换为 PEM 文件,以便我可以使用其他 API 访问它。 (此证书的初始格式为 PFX)。

我已经检查过,如果我通过 Postman 下载证书,通过“发送和下载”按钮,我会得到如下信息:

0‚
g0‚
'   *†H†÷
 ‚
‚
0‚

这与我直接写入文件的内容略有不同。我怎样才能从那个转换到这个?我在下一步遇到错误是因为这不是有效的 PFX 文件。来自其他 API 的错误如下所示:

DecodeToAsn:
            ASN.1 length cannot be more than 4 bytes in definite long-form.
            This error typically occurs when trying to decode data that is not ASN.1
            A common cause is when decrypting ASN.1 data with an invalid password,
            which results in garbage data. An attempt is made to decode the garbage bytes
            as ASN.1, and this error occurs...
          --DecodeToAsn
          Failed to decode PFX ASN.1 for integrity verification.

那么我怎样才能正确地将字节数组存储到本地文件中呢?或者有什么方法可以通过 Postman 将字节数组转换为我所拥有的?

目前我只将字节数组直接写入文件,下面是代码:

async function downloadCertificate() {
    try {
        let pfx = new chilkat.Pfx();

        let downloadedPfxByteArray = await Api.downloadCertificate(id);
        let pfxFileLocation = `${process.cwd()}\\media\\CERTFILE.pfx`;

        fs.writeFileSync(pfxFileLocation, downloadedPfxByteArray);

        pfx.LoadPfxFile(pfxFileLocation, 'password');
        let strPem = pfx.ToPem();

        console.log(strPem);

        return pemValue;
    } catch (error) {
        console.log(`READ PFX FAIL ! ${error}`);
    }
}

感谢您的阅读,如果有人可以提供帮助,我们将不胜感激!

【问题讨论】:

  • 您可以将文件内容转换为HEX,然后您可以获取文件的md5进行比较,或者您可以使用此文件创建一个zip文件。
  • @dnaz 嗯不确定其他API是否接受hex文件,我认为它只接受PFX文件,你的意思是我得到bytearray后,我将它作为hex存入文件?跨度>
  • 是的,如果文件没有大尺寸。

标签: javascript typescript unicode utf-8 chilkat


【解决方案1】:
#!/usr/bin/env node
const fetch = require('node-fetch');
const fs = require('fs').promises;

async function main() {
    await fs.writeFile(
        '/tmp/so-58603015.pfx',
        Buffer.from(await (await fetch('…url…')).arrayBuffer())
    );
}

main();

【讨论】:

  • 是的第 17 行是我将从 PFX 文件中提取证书和密钥的代码,但它可能不是有效的 PFX 文件,因此会引发错误。我在本地有我的字节数组,所以可能不需要获取?这也是本地控制台应用程序。谢谢!
  • 考虑提供一些附带的文字来描述您的代码如何解决问题以及它是如何工作的。
  • 模糊的问题,模糊的答案。
  • 我已经添加了代码和完整的错误,希望让它变得不那么模糊。
猜你喜欢
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 2016-04-03
  • 2018-11-21
  • 2019-12-14
  • 1970-01-01
  • 2021-05-21
相关资源
最近更新 更多