Node.js有内置的Base64编码了吗?

我问这个问题的原因是crypto的final()只能输出十六进制、二进制或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编码我的加密十六进制输出。


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

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

Buffers是一个全局对象,因此不需要require。用字符串创建的缓冲区可以接受一个可选的编码参数来指定字符串的编码方式。可用的toString和Buffer构造函数编码如下:

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


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

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

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

代码片段应该如下所示:

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

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


我使用下面的代码来解码Node.js API中的Base64字符串,Node.js版本10.7.0:

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开发中使用了上面的代码。


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

你可以通过npm安装Buffer

你可以像这样在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

我创建了一个终极的小型JavaScript npm库,用于在Node.js中进行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

您可以使用简单的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编码器解码器中实现的。