如何在node.js中进行base64编码?

How to do Base64 encoding in node.js?

node.js是否有内置的base64编码?

我之所以这样问是因为来自cryptofinal()只能输出十六进制、二进制或ASCII数据。例如:

1
2
3
4
5
6
7
var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'hex');
ciph += cipher.final('hex');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'hex', 'utf8');
txt += decipher.final('utf8');

根据文档,update()可以输出base64编码的数据。但是,final()不支持base64。我试过了,它会坏的。

如果我这样做:

1
2
var ciph = cipher.update(plaintext, 'utf8', 'base64');
    ciph += cipher.final('hex');

那么我应该用什么来解密呢?十六进制还是BASE64?

因此,我在寻找一个函数base64编码我的加密十六进制输出。

谢谢。


缓冲区可用于获取字符串或数据段,并对结果进行base64编码。例如:

1
2
3
4
> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

缓冲区是全局对象,因此不需要任何要求。使用字符串创建的缓冲区可以使用可选的编码参数来指定字符串的编码方式。可用的toStringBuffer构造函数编码如下:

'ascii' - for 7 bit ASCII data only. This encoding method is very
fast, and will strip the high bit if set.

'utf8' - Multi byte encoded
Unicode characters. Many web pages and other document formats use
UTF-8.

'ucs2' - 2-bytes, little endian encoded Unicode characters. It
can encode only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).

'base64' - Base64 string encoding.

'binary' - A way of encoding raw
binary data into strings by using only the first 8 bits of each
character. This encoding method is deprecated and should be avoided in
favor of Buffer objects where possible. This encoding will be removed
in future versions of Node.


接受的答案包含在大于6的节点版本中被视为安全问题的内容(尽管在这个用例中,输入可能总是被强制为字符串)。

根据文档,不推荐使用Buffer构造函数。

下面是一个在WS-Library中使用漏洞的例子。

代码段应为:

1
2
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));


Crypto现在支持base64(引用):

1
cipher.final('base64')

所以你可以简单地做:

1
2
3
4
5
6
7
var cipher = crypto.createCipheriv('des-ede3-cbc', encryption_key, iv);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');

var decipher = crypto.createDecipheriv('des-ede3-cbc', encryption_key, iv);
var txt = decipher.update(ciph, 'base64', 'utf8');
txt += decipher.final('utf8');