Node.js 中的 crypto.randomBytes() 方法
crypto.randomBytes() 會生成密碼學上可靠的偽隨機資料。在建立的位元組中沒有足夠的熵之前,此方法不會完成。但在那之後,它也不會花費超過幾毫秒的時間。此方法基本上會建立一些隨機位元組,然後進一步使用這些位元組。
語法
crypto.randomBytes(size, [callback])
引數
以上引數的說明如下 −
size – 此引數定義要生成的位元組數。大小不得大於 2**31 – 1。
callback – 如果該方法中出現任何錯誤,則會呼叫回撥。
示例
建立一個名為 – randomBytes.js 的檔案,並複製下面的程式碼片段。建立檔案後,使用以下命令執行此程式碼,如下面的示例中所示 −
node randomBytes.js
randomBytes.js
// crypto.randomBytes() Asynchronous demo example
// Importing the crypto module
const crypto = require('crypto');
crypto.randomBytes(64, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});輸出
C:\home
ode>> node randomBytes.js 64 bytes of random data: eb2bcebb999407286caea729998e7fa0c089178f8ca43857e73ea3ff66dbe1852af24a4b0199be 9192798a3f8ad6d6475db3621cfacf38dcb0fba5d77d73aaf5
示例
我們再來看一個示例。
// crypto.randomBytes() Synchronous demo example
// Importing the crypto module
const crypto = require('crypto');
const buffer = crypto.randomBytes(256);
console.log(
`${buffer.length} bytes of random data: ${buffer.toString('base64')}`);輸出
C:\home
ode>> node randomBytes.js 256 bytes of random data: n7yfRMo/ujHfBWSF2VFdevG4WRbBoG9Fqwu51+/9ZBUV6Qo88YG7IbcEaIer+g+OgjMv4RyNQ6/67a F5xWmkOR3oA6J6bdAJ1pbstTuhIfItF1PQfP26YXk1QlaoKy/YJxPUngyK4kNG9O04aret4D+2qIq9 BUaQcv+R9Xi014VKNUDZ+YQKEaLHBhJMq6JgehJ56iNbdNJ4+PN7SQwjNdZ8gS76izAwYsSZ7Kuyx2 VzdXIKsLmjleuJ2DZ7/6Yyn8WM9463dhuh0KQ5nwFbgzucvjmdvDjBlGFZBGlKs6AXqYh+0Oe6Ckkv 3OpnXOJs+GExbmnvjaeDQ03khpdJfA==
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP