【问题标题】:How can I do Base64 encoding in Node.js?如何在 Node.js 中进行 Base64 编码?
【发布时间】:2011-09-05 03:43:34
【问题描述】:

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

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

【问题讨论】:

标签: node.js encoding base64


【解决方案1】:

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

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

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

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

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

'ucs2' - 2 字节,小端编码的 Unicode 字符。它 只能编码 BMP(Basic Multilingual Plane, U+0000 - U+FFFF)。

'base64' - Base64 字符串编码。

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

【讨论】:

  • const atob = (data) => Buffer.from(data, 'base64').toString('ascii');
  • 应该是.toString("binary")(毕竟atob代表ascii(base64)到二进制)
  • @12Me21 我以为它代表 ascii to base64?
  • @DavidCallanan atob() 从 base64 转换
  • 我在Buffer.from (node:13765) [DEP0005] DeprecationWarning: Buffer() 因安全性和可用性问题而被弃用后收到此警告。请改用 Buffer.alloc()、Buffer.allocUnsafe() 或 Buffer.from() 方法。
【解决方案2】:

crypto 现在支持 Base64 (reference):

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

【讨论】:

  • 有什么理由在 NotJavanese 的回答中使用这个?
  • 必须匹配 Node 和 Python 之间的加密,这个答案为我节省了一个问题!谢谢:)
  • 这是不正确的,因为您不能只附加多个 base64 字符串并获得正确连接的 base64 字符串。这仅适用于更新函数返回长度可被 4 整除的块,其中不能保证。
【解决方案3】:

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

根据the documentation,不推荐使用Buffer 构造函数。

这是一个example of a vulnerability,可以在ws 库中使用它。

代码 sn-ps 应为:

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

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

【讨论】:

  • 当我尝试使用您的第一行时,Node 返回:[TypeError: this is not a typed array.]
  • 这个错误发生在早于 v6 的节点版本上。在这些版本中,您需要使用构造函数 (new Buffer) 而不是 Buffer.from
  • Buffer.from() 在 v4.5.0 中添加。
  • 只是为了节省您几分钟,因为我试图查看此示例与已接受答案中的示例之间的差异,因此现在已将已接受答案更新为此答案所建议的内容。
  • 什么是“ws”库?你可以添加参考吗?但是没有“编辑:”、“更新:”或类似的 - 答案应该看起来好像是今天写的。
【解决方案4】:

我正在使用以下代码在 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 开发中使用上述行代码。

【讨论】:

    【解决方案5】:

    缓冲区可用于获取字符串或数据片段并对结果进行 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
    

    【讨论】:

    • buffer 应大写为Buffer
    • @RedwolfPrograms 如你所见,我最后导入了这个require('buffer/').Buffer;,你可以看到Buffer
    【解决方案6】:

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

    安装

    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
    

    【讨论】:

    • nodejs原生支持不需要额外安装插件
    【解决方案7】:

    您可以使用简单的 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 encoder decoder中实现的。

    【讨论】:

    • 也许将其更新为“Hello, World!”(不是“Hello World!”)?
    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2011-04-16
    • 2017-11-11
    • 2012-10-26
    • 1970-01-01
    • 2010-09-17
    相关资源
    最近更新 更多