How to Base64 encode an AES Encrypted Buffer
Asked Answered
C

1

7

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 !

Chlorothiazide answered 22/1, 2019 at 10:6 Comment(0)
A
18

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
Ananna answered 22/1, 2019 at 10:23 Comment(4)
Why encrypt the buffer?Clive
@OneCricketeer, why do you ask this question?Ananna
I mean, I see the OP encrypted the data, yes, but buf.toString('base64') works on its ownClive
@OneCricketeer, yes, OP could use buf.toString('base64'), but my point was to show also what was his problem and a possible solution in case he needed stringified encrypted buffer. In the post question he did mention in text that he tried to use the buffer method, but in code he was calling the .toSting() method of the encrypted Uint8Array, and I assumed he wanted the base64 display of the encrypted buffer.Ananna

© 2022 - 2024 — McMap. All rights reserved.