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

1221

Node.js现在是否内置了Base64编码?

我之所以问这个问题是因为来自cryptofinal()只能输出十六进制、二进制或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');

根据文档,update() 方法可以输出 Base64 编码的数据。然而,final() 不支持 Base64。我尝试过了,这样做会导致出错。

如果我这样做:

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

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

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


14
对于在2016年或之后遇到此问题的人,cipher.final('base64')是有效的解决方法。 - avck
尝试使用 Base122 https://github.com/kevinAlbs/Base122 - tim
8个回答

2695

缓冲区可以用于将字符串或数据片段进行Base64编码。例如:

> console.log(Buffer.from("Hello World").toString('base64'));
SGVsbG8gV29ybGQ=
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World
Buffer构造函数是一个全局对象,因此不需要使用require。使用字符串创建的缓冲区可以使用可选的编码参数来指定字符串的编码方式。可用的toStringBuffer构造函数的编码方式如下:

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

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

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

'base64' - Base64字符串编码。

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


3
const atob = (data) => Buffer.from(data, 'base64').toString('ascii'); - spencer.sm
@12Me21 我认为它代表 ASCII 转 Base64? - David Callanan
@DavidCallanan 的 atob() 函数可以将 base64 编码转换为原始数据。 - 12Me21
在使用 Buffer.from 后,我收到了以下警告 (node:13765) [DEP0005] DeprecationWarning: Buffer() 由于安全性和易用性问题已被弃用。请改用 Buffer.alloc()、Buffer.allocUnsafe() 或 Buffer.from() 方法。 - JRichardsz
我有一个相关的问题,我认为你会知道答案。感谢你的帮助!https://dev59.com/kX8QtIcB2Jgan1zn4nNr - Ryan
显示剩余2条评论

375

接受的答案以前包含new Buffer(),在Node.js 6以上的版本中被认为是一个安全问题(尽管对于这种情况,输入似乎总是可以被强制转换为字符串)。

根据文档Buffer构造函数已被弃用。

代码片段应该改写为:

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

在撰写这个答案之后,它已经得到更新,并且现在与此匹配。


当我尝试使用你的第一行时,Node 返回: [TypeError: this is not a typed array.] - Dave Voyles
8
此错误发生在Node版本低于v6的情况下。在这些版本中,您需要使用构造函数(new Buffer)而不是Buffer.from - NotJavanese
Buffer.from() 是在 v4.5.0 版本中添加的。 - dskrvk
99
为了节省你几分钟的时间,我浪费了这些时间来比较这个示例和被接受答案中的一个例子的区别。现在被接受答案已经更新到与这个答案所建议的相同。 - Kunok
什么是“ws”库?你能添加一个参考吗?但是请不要包含“编辑:”,“更新:”或类似的内容 - 回答应该看起来像今天写的。 - Peter Mortensen

51

crypto现在支持Base64 (参考):


cipher.final('base64')

那么你可以简单地执行以下操作:

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

3
相较于NotJavanese的答案,使用这个的任何理由? - Trevor
3
必须在Node和Python之间匹配加密,这个答案帮了我大忙!谢谢 :) - GigiSan
2
这是不正确的,因为您不能仅附加多个base64字符串并获得正确连接的base64字符串。只有在更新函数返回长度可被4整除的块时才有效,但无法保证这一点。 - phiresky

12

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

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

您可以在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

1
buffer should be capitalized to Buffer - Radvylf Programs
1
@RedwolfPrograms,你可以看到我在最后导入了require('buffer/').Buffer;,你可以看到Buffer - Vishal Thakur

3
我正在使用以下代码在Node.js API (版本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 + '"');

请不要在浏览器控制台中尝试运行上述代码,它不起作用。将代码放入Node.js的服务器端文件中。我正在API开发中使用上述行代码。

2
试着这样做:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

这将把一个字符串转换成base64编码的字符串,即SGVsbG8gV29ybGQ=,然后你可以解码回Hello World

-2

我已经为Node.js创建了一个终极小型的JavaScript npm库,用于Base64编码/解码转换。

安装

npm install nodejs-base64-converter --save

使用方法

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

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

10
Node.js本身支持该功能,无需安装额外插件。 - Mederic

-3
你可以使用简单的JavaScript进行Base64编码和解码。
$("input").keyup(function () {
    var value = $(this).val(),
        hash = Base64.encode(value);
    $(".test").html(hash);

    var decode = Base64.decode(hash);

    $(".decode").html(decode);
});

var Base64 = {_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the string
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the string
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"</script></div>

这是在Base64编码解码器中实现的。


1
也许可以更新一下“Hello, World!”(不是“Hello World!”)的内容? - Peter Mortensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接