larry*wei 2011-05-31 02:09 采纳率: 0%
浏览 312
已采纳

如何在 node.js 中实现 Base64编码?

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

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

According to the docs, update() can output base64-encoded data. However, final() doesn't support base64. I tried and it will break.

If I do this:

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

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

Therefore, I'm looking for a function to base64-encode my encrypted hex output.

Thanks.

转载于:https://stackoverflow.com/questions/6182315/how-to-do-base64-encoding-in-node-js

  • 写回答

3条回答 默认 最新

  • 笑故挽风 2011-05-31 02:46
    关注

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

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)