Mô tả
Phương thức crypto.randomBytes() tạo dữ liệu ngẫu nhiên giả mã hóa mạnh (cryptographically strong pseudo-random data). Phương thức này sẽ không hoàn thành cho đến khi có đủ entropy trong các byte được tạo. Nhưng ngay cả sau đó nó cũng không mất quá vài mili giây. Phương thức này cơ bản tạo ra một vài byte ngẫu nhiên dùng cho các mục đích khác.
Cú pháp
crypto.randomBytes(size, [callback])
Tham số
size – Đối số này định nghĩa số byte cần tạo. Size không được lớn hơn 2**31 - 1.
callback – Callback được gọi nếu có lỗi xảy ra trong phương thức.
Ví dụ
Tạo file tên randomBytes.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
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')}`); });Đầu ra
C:\home\node>> node randomBytes.js 64 bytes of random data: eb2bcebb999407286caea729998e7fa0c089178f8ca43857e73ea3ff66dbe1852af24a4b0199be 9192798a3f8ad6d6475db3621cfacf38dcb0fba5d77d73aaf5
Ví dụ khác
Xem thêm một ví dụ nữa.
// 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')}`);Đầu ra
C:\home\node>> 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==