Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Phương thức crypto.randomFillSync() trong Node.js


Phương thức crypto.randomFillSync() nhận tham số buffer và trả về buffer đã được điền giá trị ngẫu nhiên mã hóa. Theo tên gọi, đây là quá trình đồng bộ (sync).

Cú pháp

crypto.randomFillSync(buffer, [offset], [size])

Tham số

  • buffer – Chứa dữ liệu. Kiểu: string, TypedArray, Buffer, ArrayBuffer, DataView. Kích thước không vượt quá 2**31-1.

  • offset – Vị trí bắt đầu điền. Mặc định: 0.

  • size – Kích thước sau offset (buffer.length - offset). Không vượt quá 2**31-1.

Ví dụ

Tạo file randomFillSync.js và sao chép mã. Chạy lệnh:

node randomFillSync.js

randomFillSync.js

// Demo crypto.randomFillSync()
// Import module crypto
const crypto = require('crypto');

// Định nghĩa buffer độ dài 15
const buffer = Buffer.alloc(15);
// Buffer
console.log(crypto.randomFillSync(buffer).toString('base64'));
// Buffer và Offset
crypto.randomFillSync(buffer, 4);
console.log(buffer.toString('base64'));
// Buffer, offset và size
crypto.randomFillSync(buffer, 4, 4);
console.log(buffer.toString('base64'));

Kết quả

C:\home\node>> node randomFillSync.js
wVBZ+i/nvmL3Ce4kBOl0
wVBZ+hkP5DB/4Ci8yTGs
wVBZ+stVWJZ/4Ci8yTGs

Ví dụ 2

Ví dụ với TypedArray (Int8Array, BigInt64Array) và DataView.

// Demo crypto.randomFillSync()
// Import module crypto
const crypto = require('crypto');

// Tạo Int8Array
const data = new Int8Array(16);
console.log(Buffer.from(crypto.randomFillSync(data).buffer, data.byteOffset, data.byteLength).toString('base64'));
console.log();

// Tạo BigInt64Array
const data2 = new BigInt64Array(4);
console.log(Buffer.from(crypto.randomFillSync(data2).buffer, data2.byteOffset, data2.byteLength).toString('ascii'));
console.log();

// Tạo DataView
const data3 = new DataView(new ArrayBuffer(7));
console.log(Buffer.from(crypto.randomFillSync(data3).buffer, data3.byteOffset, data3.byteLength).toString('hex'));

Kết quả

C:\home\node>> node randomFillSync.js
iNm8tiwDATcV6I8xjTSTbQ==
ra+I=(6&Xse"hjw?!EO?D#S7M
d957fb1dbdfa00