Skip to content

fix(ciphers): XORCipher now encrypts newline characters - #312

Open
Ankur-Kataria wants to merge 2 commits into
TheAlgorithms:masterfrom
Ankur-Kataria:master
Open

fix(ciphers): XORCipher now encrypts newline characters#312
Ankur-Kataria wants to merge 2 commits into
TheAlgorithms:masterfrom
Ankur-Kataria:master

Conversation

@Ankur-Kataria

Copy link
Copy Markdown

Description

Fixes #308 — XORCipher was silently skipping newline (\n, \r, etc.) characters instead of encrypting them.

Root cause

The implementation used str.replace(/./g, ...). In JavaScript/TypeScript, the . metacharacter without the s (dotAll) flag does not match line-terminator characters (\n U+000A, \r U+000D, U+2028, U+2029). Those bytes were passed through unchanged, which is both a correctness bug and an information leak.

// Before — \n is silently passed through
str.replace(/./g, (char) => String.fromCharCode(char.charCodeAt(0) ^ key))

// After — Array.from iterates every character including line terminators
Array.from(str, (char) => String.fromCharCode(char.charCodeAt(0) ^ key)).join('')

What changed

File Change
ciphers/xor_cipher.ts Replace regex-based replacement with Array.from()
ciphers/test/xor_cipher.test.ts Add two new test cases covering \n/\r and self-inverse property

Tests

All 3 tests pass (npm test -- --testPathPattern=xor_cipher):

  • passing a string & number as an argument — existing case unchanged ✓
  • encrypts newline and other line-terminator characters — new ✓
  • XORCipher is its own inverse — new ✓

…gorithms#308)

The previous implementation used str.replace(/./g, ...) where the dot
metacharacter does not match line-terminator characters (\n, \r, etc.)
without the s (dotAll) flag, so those bytes were silently passed through
unencrypted — an information leak and a correctness bug.

Replace the regex-based replacement with Array.from(), which iterates
over every character regardless of whether it is a line terminator.
The cipher logic (XOR with key) and the return type are unchanged.

Add two new test cases:
  - encrypts \n and \r correctly (previously left unchanged)
  - XORCipher is its own inverse, including strings with newlines
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ciphers/xor_cipher: XORCipher leaves newline-class characters un-encrypted (regex /./g skips line terminators)

1 participant