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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6182315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:14:53  来源:igfitidea点击:

How to do Base64 encoding in node.js?

node.jsencodingbase64

提问by murvinlai

Does node.js have built-in base64 encoding yet?

node.js 有内置的 base64 编码吗?

The reason why I ask this is that final()from cryptocan only output hex, binary or ascii data. For example:

我问这个的原因是final()fromcrypto只能输出十六进制、二进制或 ascii 数据。例如:

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');

According to the docs, update()can output base64-encoded data. However, final()doesn't support base64. I tried and it will break.

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

If I do this:

如果我这样做:

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

Then what should I use for decryption? Hex or base64?

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

Therefore, I'm looking for a function to base64-encode my encrypted hex output.

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

回答by onteria_

Bufferscan be used for taking a string or piece of data and doing base64 encoding of the result. For example:

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

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

Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toStringand Bufferconstructor encodings are as follows:

缓冲区是一个全局对象,因此不需要 require。使用字符串创建的缓冲区可以采用可选的编码参数来指定字符串采用的编码。可用的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.

'ascii' - 仅适用于 7 位 ASCII 数据。这种编码方式非常快,如果设置了会去掉高位。

'utf8' - 多字节编码的 Unicode 字符。许多网页和其他文档格式使用 UTF-8。

'ucs2' - 2 字节、小端编码的 Unicode 字符。它只能编码 BMP(基本多语言平面,U+0000 - U+FFFF)。

'base64' - Base64 字符串编码。

'binary' - 一种仅使用每个字符的前 8 位将原始二进制数据编码为字符串的方法。这种编码方法已被弃用,应尽可能避免使用 Buffer 对象。此编码将在 Node.js 的未来版本中删除。

回答by NotJavanese

The accepted answer previously containednew Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

先前包含的已接受答案new Buffer()被认为是大于 6 的节点版本中的安全问题(尽管对于此用例来说,输入似乎总是可以被强制转换为字符串)。

The Bufferconstructor is deprecated according to the documentation.

Buffer构造是根据过时文件

Here is an example of a vulnerabilitythat can result from using it in the ws library.

以下是在 ws 库中使用它可能导致的漏洞示例

The code snippets should read:

代码片段应为:

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

After this answer was written, it has been updated and now matches this.

写完这个答案后,它已经更新,现在与此匹配。

回答by Javier Ferrero

crypto now supports base64 (reference):

加密现在支持 base64(参考):

cipher.final('base64') 

So you could simply do:

所以你可以简单地做:

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');

回答by Vishal Thakur

Bufferscan be used for taking a string or piece of data and doing base64 encoding of the result. For example:

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

You can install Buffervia npm like :- npm i buffer --save

您可以通过 npm安装Buffer,例如:-npm i buffer --save

you can use this in your jsfile like this :-

你可以js像这样在你的文件中使用它:-

var buffer = require('buffer/').Buffer;

->> console.log(buffer.from("Hello Vishal Thakur").toString('base64'));
SGVsbG8gVmlzaGFsIFRoYWt1cg==  // Result

->> console.log(buffer.from("SGVsbG8gVmlzaGFsIFRoYWt1cg==", 'base64').toString('ascii'))
Hello Vishal Thakur   // Result

回答by Manish Prajapati

I have created a ultimate small js npmlibrary for the base64 encode/decode conversion in Node.js.

我为 Node.js 中的 base64 编码/解码转换创建了一个最终的小型 js npm库。

Installation

安装

npm install nodejs-base64-converter --save

Usage

用法

var nodeBase64 = require('nodejs-base64-converter');

console.log(nodeBase64.encode("test text")); //dGVzdCB0ZXh0
console.log(nodeBase64.decode("dGVzdCB0ZXh0")); //test text

回答by Devendra Chhaiya

I am using following code to decode base64 string in node API nodejs version 10.7.0

我正在使用以下代码来解码 node API nodejs 版本 10.7.0 中的 base64 字符串

let data = 'c3RhY2thYnVzZS5jb20=';  // Base64 string
let buff = new Buffer(data, 'base64');  //Buffer
let text = buff.toString('ascii');  //this is the data type that you want your Base64 data to convert to
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"'); 

Please don't try to run above code in console of the browser, won't work. Put the code in server side files of nodejs. I am using above line code in API development.

请不要尝试在浏览器的控制台中运行上面的代码,不会工作。将代码放在 nodejs 的服务器端文件中。我在 API 开发中使用上面的代码。