Node.js 中的 crypto.createCipheriv() 方法


crypto.createCipheriv() 方法首先根據給定的金鑰和授權因子 (iv) 建立並返回密碼物件。

語法

crypto.createCipheriv(algorithm, key, iv, options)

引數

以上引數描述如下:

  • algorithm – 它接收用於建立密碼的演算法的輸入。一些可能的值是:aes192、aes256 等。

  • key – 它接收演算法和 iv 使用的原始金鑰的輸入。可能的值可以是:字串、緩衝區、TypedArray 或 DataView 型別。它可以選擇是 secret 型別的物件。

  • iv – 也稱為初始化向量。此引數接收 iv 的輸入,這將使密碼不確定且唯一。它不需要保密。其可能的值型別為:字串、緩衝區、TypedArray、DataView。如果密碼不需要,則可以為 null。

  • options – 這是一個可選引數,用於控制流行為。當密碼在 CCM 或 OCB 模式下使用時(例如 'aes-256-ccm'),此引數不是可選的。

示例

建立一個名為 createCipheriv.js 的檔案並複製下面的程式碼片段。建立檔案後,使用以下命令執行此程式碼,如下例所示:

node createCipheriv.js

createCipheriv.js

 線上演示

// A node demo program for creating the ECDH

// Importing the crypto module
const crypto = require('crypto');

// Initializing the algorithm
const algorithm = 'aes-256-cbc';

// Initializing the key
const key = crypto.randomBytes(32);

// Initializing the iv vector
const iv = crypto.randomBytes(16);

// Creating the function to encrypt data
function encrypt(text) {

// Creating the cipher with the above defined parameters
let cipher = crypto.createCipheriv(
   'aes-256-cbc', Buffer.from(key), iv);

let encrypted = cipher.update(text);

encrypted = Buffer.concat([encrypted, cipher.final()]);

// Returning iv and the encrypted data
return { iv: iv.toString('hex'),
   encryptedData: encrypted.toString('hex') };
}
// Printing public & private curve keys...
var output = encrypt("TutorialsPoint");
console.log(output);

輸出

C:\home
ode>> node createCipheriv.js { iv: '3dd899aa441c00d4d8d2ff95abb2e684', encryptedData: 'b4985053bc1507fc25a4d99823dc8b03' }

示例

讓我們再看一個例子。

// A node demo program for creating the ECDH

// Importing the crypto module
const crypto = require('crypto');

// Initializing the algorithm
const algorithm = 'aes-192-cbc';

// Defining and initializing the password
const password = '123456789'

// Initializing the key
const key = crypto.scryptSync(password, 'TutorialsPoint', 24);

// Initializing the iv vector
const iv = Buffer.alloc(16, 0);

// Creating the cipher with the above defined parameters
const cipher = crypto.createCipheriv(algorithm, key, iv);

let encrypted = '';

// Reading and encrypting the data
cipher.on('readable', () => {
   let chunk;
   while (null !== (chunk = cipher.read())) {
      encrypted += chunk.toString('base64');
   }
});

//Handling the closing/end event
cipher.on('end', () => {
   console.log(encrypted);
});

// Printing public & private curve keys...
cipher.write('TutorialsPoint');
cipher.end();
console.log("Completed... !");

輸出

C:\home
ode>> node createCipheriv.js Completed... ! uqeQEkXy5dpJjQv+JDvMHw==

更新於:2021年5月20日

4K+ 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.