如何在 Node.js 中进行 Base64 编码? [英] How can I do Base64 encoding in Node.js?

查看:29
本文介绍了如何在 Node.js 中进行 Base64 编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Node.js 有内置 Base64 编码吗?

Does Node.js have built-in Base64 encoding yet?

我问这个的原因是 crypto 中的 final() 只能输出十六进制、二进制或 ASCII 数据.例如:

The reason why I ask this is that final() from crypto can only output hexadecimal, binary or ASCII data. For example:

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.我试过了,它会坏的.

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

如果我这样做:

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

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

Then what should I use for decryption? Hexadecimal or Base64?

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

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

推荐答案

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

Buffers can be used for taking a string or piece of data and doing Base64 encoding of the result. For example:

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

缓冲区是一个全局对象,所以不需要.使用字符串创建的缓冲区可以采用可选的编码参数来指定字符串采用的编码.可用的 toStringBuffer 构造函数编码如下:

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 toString and Buffer constructor encodings are as follows:

'ascii' - 仅用于 7 位 ASCII 数据.这种编码方式很速度快,如果设置,将剥离高位.

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

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

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

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

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

'base64' - Base64 字符串编码.

'base64' - Base64 string encoding.

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

'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.

这篇关于如何在 Node.js 中进行 Base64 编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆