fibjs/fibjs

Decryption of block requires a full block in cipher.encrypt()

Closed this issue · 1 comments

A simple example in fibjs website 对象 Cipher

C:\Users\Administrator>fibjs
Welcome to fibjs 0.36.0.
Type ".help" for more information.
> const crypto = require('crypto');
> const key = crypto.randomBytes(16); // generate a 16-byte random key
> const cipher = new crypto.Cipher(crypto.AES, crypto.ECB, key);
> const plaintext = 'Hello, world!';
> const encrypted = cipher.encrypt(plaintext);
[repl]:1:26
const encrypted = cipher.encrypt(plaintext);
                         ^
Error: CIPHER - Decryption of block requires a full block
    at [repl]:1:26

Why the default paddingMode in Cipher not PKCS7?
And throws the error "Error: CIPHER - Bad input parameters" when calling cipher.paddingMode(crypto.PKCS7).

ECB mode does not support PKCS7 padding because ECB (Electronic Codebook) mode encrypts each block of data independently without taking into account the relation between adjacent blocks. This lack of dependency makes it vulnerable to certain attacks, such as pattern recognition and dictionary attacks.

On the other hand, CBC (Cipher Block Chaining) mode uses a chaining mechanism where the previous block’s ciphertext is XORed with the current block’s plaintext before encryption. This adds randomness and dependency between blocks, making it more secure compared to ECB.

Additionally, CBC mode supports PKCS7 padding, which adds extra bytes to the plaintext to fill the last block when it is not complete. This padding scheme ensures that the original data can be properly recovered after decryption.

Therefore, it is recommended to use CBC mode along with PKCS7 padding for improved security and data integrity in encryption algorithms.