Cipher Object
সাইফার ক্লাস Node.js এর ক্রিপ্টো মডিউলের অংশ। এটি বিভিন্ন অ্যালগরিদম ব্যবহার করে ডেটা এনক্রিপ্ট করার একটি উপায় প্রদান করে। সাইফার ইনস্ট্যান্সগুলি crypto.createCipheriv() পদ্ধতি ব্যবহার করে তৈরি করা হয়।
দ্রষ্টব্য:
crypto.createCipher() Node.js v10.0.0 . crypto.createCipheriv() , (IV) .
Import Crypto Module
// Import the crypto module
const crypto = require('crypto');
// Create a cipher with createCipheriv
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32); // 32 bytes for AES-256
const iv = crypto.randomBytes(16); // 16 bytes for AES
const cipher = crypto.createCipheriv(algorithm, key, iv);
Cipher Methods
| পদ্ধতি | ব্যাখ্যা |
|---|---|
| cipher.update(data[, inputEncoding][, outputEncoding]) | ডেটা সহ সাইবার আপডেট করে। যদি ইনপুট এনকোডিং প্রদান করা হয়, ডেটা নির্দিষ্ট এনকোডিং ব্যবহার করে একটি স্ট্রিং। যদি আউটপুট এনকোডিং নির্দিষ্ট করা হয়, তবে রিটার্ন মানটি নির্দিষ্ট এনকোডিং ব্যবহার করে একটি স্ট্রিং হবে। অন্যথায়, একটি বাফার ফেরত দেওয়া হয়। |
| cipher.final([outputEncoding]) | অবশিষ্ট কোনো এনক্রিপ্ট করা বিষয়বস্তু ফেরত দেয়। যদি আউটপুট এনকোডিং নির্দিষ্ট করা হয়, একটি স্ট্রিং ফেরত দেওয়া হয়; অন্যথায়, একটি বাফার ফেরত দেওয়া হয়। |
| cipher.setAAD(buffer[, options]) | একটি AEAD অ্যালগরিদম ব্যবহার করার সময় (যেমন GCM বা CCM), অতিরিক্ত অনুমোদিত ডেটা (AAD) সেট করে। |
| cipher.getAuthTag() | একটি AEAD অ্যালগরিদম ব্যবহার করার সময়, এই পদ্ধতিটি প্রমাণীকরণ ট্যাগ ধারণকারী একটি বাফার প্রদান করে। |
| cipher.setAutoPadding([autoPadding]) | যখন অটোপ্যাডিং সত্য (ডিফল্ট), প্যাডিং ব্যবহার করা হয়। ডেটা ম্যানুয়ালি প্যাড করা থাকলে অক্ষম করুন। |
Basic Encryption Example
নিম্নলিখিত উদাহরণটি ব্যাখ্যা করে কিভাবে AES-256-CBC অ্যালগরিদম ব্যবহার করে ডেটা এনক্রিপ্ট করা যায়:
const crypto = require('crypto');
// Generate encryption key and initialization vector
// In a real application, you would securely store and retrieve these values
const key = crypto.randomBytes(32); // Key for AES-256 (32 bytes)
const iv = crypto.randomBytes(16); // IV for AES (16 bytes)
// Create a cipher
const algorithm = 'aes-256-cbc';
const cipher = crypto.createCipheriv(algorithm, key, iv);
// Data to encrypt
const plainText = 'This is a secret message';
// Encrypt the data
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('Original Text:', plainText);
console.log('Encrypted Text:', encrypted);
console.log('Key (hex):', key.toString('hex'));
console.log('IV (hex):', iv.toString('hex'));
// The encrypted message, key, and IV would be needed for decryption
Encrypting with Different Algorithms
Node.js . :
const crypto = require('crypto');
// The data to encrypt
const plainText = 'Hello, this is a test message';
// Function to encrypt data with different algorithms
function encryptWithAlgorithm(algorithm, keySize, ivSize, plainText) {
// Generate key and IV
const key = crypto.randomBytes(keySize);
const iv = crypto.randomBytes(ivSize);
// Create cipher
const cipher = crypto.createCipheriv(algorithm, key, iv);
// Encrypt data
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');
return {
algorithm,
encrypted,
key: key.toString('hex'),
iv: iv.toString('hex')
};
}
// Test different algorithms
const algorithms = [
{ name: 'aes-128-cbc', keySize: 16, ivSize: 16 },
{ name: 'aes-192-cbc', keySize: 24, ivSize: 16 },
{ name: 'aes-256-cbc', keySize: 32, ivSize: 16 },
{ name: 'aes-256-gcm', keySize: 32, ivSize: 16 }
];
algorithms.forEach(algo => {
try {
const result = encryptWithAlgorithm(algo.name, algo.keySize, algo.ivSize, plainText);
console.log(`Encrypted with ${result.algorithm}: ${result.encrypted}`);
} catch (error) {
console.error(`Error with ${algo.name}: ${error.message}`);
}
});
Encrypting Binary Data
পাঠ্য ছাড়াও আপনি বাইনারি ডেটা এনকোড করতে পারেন:
const crypto = require('crypto');
const fs = require('fs');
// Generate key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Create read and write streams
const readStream = fs.createReadStream('input.jpg');
const writeStream = fs.createWriteStream('encrypted.jpg.enc');
// Create cipher stream
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// Encrypt the file
readStream
.pipe(cipher)
.pipe(writeStream);
// Save the key and IV for decryption
fs.writeFileSync('encryption_key.txt', key.toString('hex'));
fs.writeFileSync('encryption_iv.txt', iv.toString('hex'));
writeStream.on('finish', () => {
console.log('File encryption completed');
});
Using AEAD Encryption
অ্যাসোসিয়েটেড ডেটা (AEAD) এর সাথে প্রমাণীকৃত এনক্রিপশন গোপনীয়তা এবং ডেটা অখণ্ডতা উভয়ই প্রদান করে:
const crypto = require('crypto');
// Data to encrypt
const plainText = 'Secret message';
const associatedData = 'Additional data to authenticate';
// Generate key and IV (nonce)
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(12); // 12 bytes (96 bits) is recommended for GCM
// Create cipher using AES-GCM (an AEAD algorithm)
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
// Set the Additional Authenticated Data (AAD)
cipher.setAAD(Buffer.from(associatedData));
// Encrypt the data
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');
// Get the authentication tag
const authTag = cipher.getAuthTag();
console.log('Encrypted Text:', encrypted);
console.log('Auth Tag (hex):', authTag.toString('hex'));
console.log('Key (hex):', key.toString('hex'));
console.log('IV (hex):', iv.toString('hex'));
console.log('Associated Data:', associatedData);
// All this information is needed for decryption and verification
Manual Padding Control
আপনি ম্যানুয়ালি প্যাডিং আচরণ নিয়ন্ত্রণ করতে পারেন:
const crypto = require('crypto');
// Generate key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Data to encrypt
const plainText = 'This is a test message';
// Function to encrypt with different padding options
function encryptWithPadding(usePadding) {
// Create cipher
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// Set padding option
cipher.setAutoPadding(usePadding);
try {
// Encrypt data
let encrypted = cipher.update(plainText, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
} catch (error) {
return `Error: ${error.message}`;
}
}
// With default padding (true)
console.log('With padding:', encryptWithPadding(true));
// Without padding
// This will likely fail unless data length is a multiple of the block size
console.log('Without padding:', encryptWithPadding(false));
// Example with manual padding to block size (16 bytes for AES)
function manualPadding(text) {
const blockSize = 16;
const padLength = blockSize - (text.length % blockSize);
return text + '\0'.repeat(padLength);
}
// Create cipher without auto padding
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
cipher.setAutoPadding(false);
// Manually pad the data
const paddedText = manualPadding(plainText);
console.log('Original length:', plainText.length);
console.log('Padded length:', paddedText.length);
// Encrypt manually padded data
let encrypted = cipher.update(paddedText, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('With manual padding:', encrypted);
Complete Encryption/Decryption Example
এখানে এনক্রিপশন এবং ডিক্রিপশন উভয়ই দেখানো একটি সম্পূর্ণ উদাহরণ রয়েছে:
const crypto = require('crypto');
// The message to encrypt
const message = 'This is a secret message that needs to be encrypted';
// Generate encryption key and IV
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Encryption function
function encrypt(text) {
// Create cipher
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// Encrypt data
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// Decryption function (using the Decipher class)
function decrypt(encryptedText) {
// Create decipher with the same key and IV
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// Decrypt data
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Encrypt the message
const encryptedMessage = encrypt(message);
console.log('Original Message:', message);
console.log('Encrypted Message:', encryptedMessage);
// Decrypt the message
const decryptedMessage = decrypt(encryptedMessage);
console.log('Decrypted Message:', decryptedMessage);
// Verify the result
console.log('Decryption successful:', message === decryptedMessage);
Encryption with a Password
অনেক অ্যাপ্লিকেশনের জন্য, আপনি একটি পাসওয়ার্ড থেকে এনক্রিপশন কী পেতে চাইতে পারেন:
const crypto = require('crypto');
// Password and salt
const password = 'mysecretpassword';
const salt = crypto.randomBytes(16);
// Generate a key from the password
function getKeyFromPassword(password, salt) {
// Use PBKDF2 to derive a key from the password
return crypto.pbkdf2Sync(password, salt, 100000, 32, 'sha256');
}
// Password-based encryption
function encryptWithPassword(text, password) {
// Generate key from password
const key = getKeyFromPassword(password, salt);
// Generate IV
const iv = crypto.randomBytes(16);
// Create cipher
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// Encrypt data
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
// Return encrypted data and IV (we'll need both for decryption)
return {
iv: iv.toString('hex'),
salt: salt.toString('hex'),
encryptedData: encrypted
};
}
// Password-based decryption
function decryptWithPassword(encryptedInfo, password) {
// Get the key from the password
const key = getKeyFromPassword(
password,
Buffer.from(encryptedInfo.salt, 'hex')
);
// Get the IV from encryptedInfo
const iv = Buffer.from(encryptedInfo.iv, 'hex');
// Create decipher
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// Decrypt data
let decrypted = decipher.update(encryptedInfo.encryptedData, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
// Test encryption with password
const message = 'Secret message protected by a password';
const encryptedInfo = encryptWithPassword(message, password);
console.log('Encrypted:', encryptedInfo);
// Test decryption with password
const decryptedMessage = decryptWithPassword(encryptedInfo, password);
console.log('Decrypted:', decryptedMessage);
// Try with wrong password
try {
const wrongPassword = 'wrongpassword';
const failedDecryption = decryptWithPassword(encryptedInfo, wrongPassword);
console.log('Decrypted with wrong password:', failedDecryption);
} catch (error) {
console.log('Decryption failed with wrong password:', error.message);
}
Supported Encryption Algorithms
Node.js . :
const crypto = require('crypto');
// Get all supported cipher algorithms
console.log(crypto.getCiphers());
সাধারণ অ্যালগরিদম অন্তর্ভুক্ত:
| অ্যালগরিদম | কী আকার (বাইট) | IV আকার (বাইট) | ব্যাখ্যা |
|---|---|---|---|
| aes-128-cbc | 16 | 16 | CBC মোডে 128-বিট কী সহ AES |
| aes-192-cbc | 24 | 16 | CBC মোডে 192-বিট কী সহ AES |
| aes-256-cbc | 32 | 16 | CBC মোডে 256-বিট কী সহ AES |
| aes-128-gcm | 16 | 12 | GCM মোডে 128-বিট কী সহ AES (AEAD) |
| aes-256-gcm | 32 | 12 | GCM মোডে 256-বিট কী সহ AES (AEAD) |
| chacha20-poly1305 | 32 | 12 | ChaCha20-Poly1305 (AEAD) |