如何在node.js中进行Base64编码? [英] How to do Base64 encoding in node.js?

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

问题描述

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

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

我问这个问题的原因是 final() from crypto 只能输出hex,binary或ascii数据。例如:

The reason why I ask this is that final() from crypto can only output hex, 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 docs, 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');

那么我应该用什么来解密? Hex或base64?

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编码。例如:

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

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

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

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位将raw
二进制数据编码为字符串的一种方式。在可能的情况下,这种编码方法已被弃用,应避免在
中使用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天全站免登陆