如何在Node.js中将字节数组转换为字符串?

4
我需要一个随机字节序列来生成密码哈希。在Ruby中,代码如下:
```ruby SecureRandom.bytes(32) ```
请注意,这将返回一个由32个随机字节组成的字符串。
 File.open("/dev/urandom").read(20).each_byte{|x| rand << sprintf("%02x",x)}

在Node.js中,我可以使用以下代码获取一系列随机字节:
 var randomSource = RandBytes.urandom.getInstance();
 var bytes = randomSource.getRandomBytesAsync(20);

但问题是,如何将它们转换为字符串?同时,我需要将它们包装在承诺中。这个方法可以吗:
   get_rand()
   .then(function(bytes) {
     authToken = bytes;
   })
5个回答

31

我喜欢你的回答,因为你提到了学习关于这个的地方...然而,我得到的是:<Buffer b8 92 17 4c f1 11 35 d2 04 2a 7b 94 03 5c 9c 1a d0 9d 6a 43> - 为什么不是像"saDasdkn2"这样的东西? - poseid
嗯...也许是我正在使用的Promise库,我在这里提交了一个问题:https://github.com/petkaantonov/bluebird/issues/34 - poseid
1
new Buffer(bytes) 已被弃用,现在可以使用 new Buffer.from(bytes) - 袁文涛

4

您可以直接使用 Node.js 提供的加密模块:

var Promise = require("bluebird");
var crypto = Promise.promisifyAll(require("crypto"));

crypto.randomBytesAsync(20).then(function(bytes){
    console.log('random byte string:', bytes.toString("hex"));
});

日志:

random byte string: 39efc98a75c87fd8d5172bbb1f291de1c6064849

1
这似乎是正确的答案。不确定使用randbytes有什么好处。它绝对在Windows上无法工作。(不过也没人关心... ;)) - j03m

2

randbytes 是异步工作的。如果你想将其与 promises 结合使用,你需要同时使用 Promises-lib。我以 when 为例:

var when          = require('when');
var RandBytes     = require('randbytes');
var randomSource  = RandBytes.urandom.getInstance();

function get_rand() {
  var dfd = when.defer();
  randomSource.getRandomBytes(20, function(bytes) {
    dfd.resolve( bytes.toString('hex') ); // convert to hex string
  });
  return dfd.promise;
}

// example call:
get_rand().then(function(bytes) {
  console.log('random byte string:', bytes);
});

这个答案也非常好,只是一个小细节,我正在使用bluebird库,也许我的问题就出在那里了。我参考了你的答案:https://github.com/petkaantonov/bluebird/issues/34 - poseid
我认为@Esailija的答案实际上是正确的。 - j03m

1
如果您正在使用ES6,那么这也很容易。
String.fromCharCode(...bytes)
Promise.resolve(String.fromCharCode(...bytes)) // Promise

或者

String.fromCharCode.apply(null, bytes)
Promise.resolve(String.fromCharCode.apply(null, bytes)) // Promise

0

你想将它转换为ASCII码吗?如果不需要,这是我的代码(只需1分钟):

  var z;
 randomSource.getRandomBytes(20, function(){z=arguments[0]})
 z
<Buffer c8 64 03 d1 2d 27 7d 8e 8f 14 ec 48 e2 97 46 84 5a d7 c7 2f>
 String(z)
'�d\u0003�-\'}��\u0014�H��F�Z��/'

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