Search code examples
javascriptnode.jsbase64bufferencode

How to Base64 encode an AES Encrypted Buffer


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

<prototype>: 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 !


Solution

  • 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