From d4321973bc343b94b0373fd7f9e6b2458ed38294 Mon Sep 17 00:00:00 2001 From: dbdefault Date: Thu, 12 Nov 2026 16:54:44 +0800 Subject: [PATCH] fix: XORCipher leaves newline-class characters un-encrypted Replace str.replace(/./g, ...) with Array.from(str, ...) so that every character including \\n, \\r, \\u2028, \\u2029 is XORed with the key. The dot in regex /./g does not match line terminators without the dotAll flag. Add test cases for newline, carriage return, and line separator inputs. Fixes #308 --- ciphers/test/xor_cipher.test.ts | 9 +++++++++ ciphers/xor_cipher.ts | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ciphers/test/xor_cipher.test.ts b/ciphers/test/xor_cipher.test.ts index 0607d6a3..5aa68992 100644 --- a/ciphers/test/xor_cipher.test.ts +++ b/ciphers/test/xor_cipher.test.ts @@ -5,4 +5,13 @@ describe('Testing XORCipher function', () => { expect(XORCipher('test', 32)).toBe('TEST') expect(XORCipher('TEST', 32)).toBe('test') }) + + it('XORs newline-class characters', () => { + // '\n' (U+000A) char code 10 XOR 1 = 11 + expect(XORCipher('A\nB', 1)).toBe('@\x0bC') + // '\r' (U+000D) char code 13 XOR 1 = 12 + expect(XORCipher('A\rB', 1)).toBe('@\x0cC') + // '\u2028' line separator XOR 1 + expect(XORCipher('A\u2028B', 1)).toBe('@\u2029C') + }) }) diff --git a/ciphers/xor_cipher.ts b/ciphers/xor_cipher.ts index 72d91e68..d6930191 100644 --- a/ciphers/xor_cipher.ts +++ b/ciphers/xor_cipher.ts @@ -10,6 +10,6 @@ * @return {string} encrypted string */ export const XORCipher = (str: string, key: number): string => - str.replace(/./g, (char: string) => + Array.from(str, (char: string) => String.fromCharCode(char.charCodeAt(0) ^ key) - ) + ).join('')