Decipher.final() Method in Node.js

The decipher.final() method in Node.js is used to return the remaining decrypted data from a decipher object. It is part of the crypto module's Decipher class and must be called to complete the decryption process. Once called, the decipher object cannot be used to decrypt additional data.

Syntax

decipher.final([outputEncoding])

Parameters

  • outputEncoding - Optional. The encoding format for the output. Possible values include 'utf8', 'hex', 'base64', etc. If not specified, a Buffer is returned.

Return Value

Returns a Buffer or string containing the final decrypted data, depending on whether outputEncoding is specified.

Example 1: Basic Decryption

// Example demonstrating decipher.final() method
const crypto = require('crypto');

// AES algorithm configuration
const algorithm = 'aes-192-cbc';
const password = '12345678123456789';

// Generate key and IV
const key = crypto.scryptSync(password, 'salt', 24);
const iv = Buffer.alloc(16, 0);

// Create decipher object
const decipher = crypto.createDecipheriv(algorithm, key, iv);

// Encrypted data (hex format)
const encrypted = 'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';

// Decrypt the data
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');

console.log("Decrypted text:", decrypted);
Decrypted text: Welcome to tutorials point

Example 2: Using Buffer Array

const crypto = require('crypto');

const algorithm = 'aes-192-cbc';
const password = '12345678123456789';
const key = crypto.scryptSync(password, 'salt', 24);
const iv = Buffer.alloc(16, 0);

const decipher = crypto.createDecipheriv(algorithm, key, iv);
const encrypted = 'a05e87569f3f04234812ae997da5684944c32b8776fae676b4abe9074b31cd2a';

// Store decrypted chunks in array
const chunks = [];
chunks.push(decipher.update(encrypted, 'hex', 'utf8'));
chunks.push(decipher.final('utf8'));

console.log("Complete message:", chunks.join(''));
Complete message: Welcome to tutorials point

Key Points

  • Final call - decipher.final() must be called to complete the decryption process

  • One-time use - Cannot decrypt additional data after calling final()

  • Error handling - Calling final() multiple times throws an error

  • Return type - Returns Buffer if no encoding specified, string otherwise

Conclusion

The decipher.final() method completes the decryption process and returns any remaining decrypted data. It's essential for properly finishing the decryption workflow and must only be called once per decipher object.

Updated on: 2026-03-15T23:19:00+05:30

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements