如何做到在node.js的Base64编码? [英] How to do Base64 encoding in node.js?

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

问题描述

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

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

我之所以问这个是决赛()加密只能输出十六进制,二进制或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');

根据文档,更新()可输出的base64恩codeD数据。然而,决赛()不支持的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');

那么我应该怎么用解密?十六进制或Base64?

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

所以,我正在寻找一个函数的base64 EN code我加密的十六进制输出。

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 缓存构造编码如下:

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' - 多字节连接codeD
  UNI code字符。许多网页和其他文档格式使用
  UTF-8。

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

UCS2' - 2字节,小端连接codeD的Uni code字符。它
  可以连接code只有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.

二进制 - 原编码的一种方式
  二进制数据转换成字符串通过仅使用每个第一8位
  字符。这种编码方法被德precated并应避免
  有利于缓冲的对象,在可能的情况。这种编码将被删除
  在节点的未来版本。

'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天全站免登陆