【问题标题】:How to encode a Buffer to Base64 in NodeJS如何在 NodeJS 中将缓冲区编码为 Base64
【发布时间】:2019-06-15 18:36:19
【问题描述】:

我正在尝试将缓冲区编码为 base64 字符串,但它只是将数组复制粘贴到字符串中而不对其进行编码。

我要编码的缓冲区是:

Uint8Array(16)

0:120

1:207

2:91

3:215

4:169

5:206

6:208

7:145

8:250

9:19

10:191

11:254

12:154

13:209

14:47

15:122

缓冲区:ArrayBuffer { byteLength: 16 }

字节长度:16

字节偏移:0

长度:16

: Uint8ArrayPrototype { … }

我尝试使用 buffer.toString('base64'),正如您将在下面看到的,但它不起作用

我使用的代码如下:

var buf = Buffer.from([18, 5, 2, 7, 32, 12, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
    var aesCbc = new aesjs.ModeOfOperation.cbc(key);
    var encryptedBytes = aesCbc.encrypt(buf);
    console.log(encryptedBytes)
    var string64 = encryptedBytes.toString('base64');
    console.log(string64)

我希望有这样的字符串:

eAnguAGneSD+Y/jOpikpnQ==(只是base64字符串的一个例子)

但结果是:

字符串:120,207,91,215,169,206,208,145,250,19,191,254,154,209,47,122

感谢您的宝贵时间!

【问题讨论】:

    标签: javascript node.js base64 buffer encode


    【解决方案1】:

    您正在尝试将 Uint8Array 值编码为 base64,而不是实际上的缓冲区,您必须使用以下方法从中创建一个缓冲区:

    var encryptedBytes = Buffer.from(aesCbc.encrypt(buf));
    
    encryptedBytes.toString('base64'); // your base64 string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-30
      • 2023-03-02
      • 1970-01-01
      • 2021-12-21
      • 2021-10-29
      • 2018-04-15
      • 1970-01-01
      • 2010-12-21
      相关资源
      最近更新 更多