简体   繁体   中英

How to encode a Buffer to Base64 in NodeJS

I'm trying to encode a buffer to a base64 string but it just copy paste the array into a string and do not encode it.

The Buffer i'm trying to encode is :

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

buffer: ArrayBuffer { byteLength: 16 }

byteLength: 16

byteOffset: 0

length: 16

: Uint8ArrayPrototype { … }

I tried to use buffer.toString('base64') as you'll see just under but it didn't work

the code i'm using for this is the following :

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)

i expect a string like this :

eAnguAGneSD+Y/jOpikpnQ== (it's just an example of a base64 string)

but the result is :

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

Thanks for your time !

You are trying to encode to base64 an Uint8Array value, not actually a buffer, you have to create a buffer out of it by using this:

var encryptedBytes = Buffer.from(aesCbc.encrypt(buf));

encryptedBytes.toString('base64'); // your base64 string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM