diff --git a/Ciphers/KeywordShiftedAlphabet.js b/Ciphers/KeywordShiftedAlphabet.js index 2c6f91fe48..a6fbba57e9 100644 --- a/Ciphers/KeywordShiftedAlphabet.js +++ b/Ciphers/KeywordShiftedAlphabet.js @@ -46,13 +46,12 @@ const alphabet = [ ] function checkKeywordValidity(keyword) { - keyword.split('').forEach((char, index) => { - const rest = keyword.slice(0, index) + keyword.slice(index + 1) - if (rest.indexOf(char) !== -1) { - return false - } - }) - return true + // Compare case-insensitively: the translation table is built from the + // lowercased keyword, so 'Kk' would collapse to a duplicate there. + const chars = keyword.toLowerCase().split('') + // forEach cannot return early, so use every: each character must be the + // first occurrence of itself. + return chars.every((char, index) => chars.indexOf(char) === index) } function getEncryptedAlphabet(keyword) { diff --git a/Ciphers/test/KeywordShiftedAlphabet.test.js b/Ciphers/test/KeywordShiftedAlphabet.test.js index 38e0839488..27307b3b34 100644 --- a/Ciphers/test/KeywordShiftedAlphabet.test.js +++ b/Ciphers/test/KeywordShiftedAlphabet.test.js @@ -11,3 +11,15 @@ test('The Algorithms === decrypt(encrypt(The Algorithms))', () => { const result = decrypt('keyword', encrypt('keyword', word)) expect(result).toMatch(word) }) + +test('rejects keywords with repeated characters', () => { + // 'HELLO' repeats L; encrypt must throw instead of producing + // ciphertext that cannot be decrypted back + expect(() => encrypt('HELLO', 'ATTACK AT DAWN')).toThrow('Invalid keyword!') + expect(() => decrypt('HELLO', 'HSSHLG HS LHVK')).toThrow('Invalid keyword!') +}) + +test('rejects keywords that repeat a character in another case', () => { + // the table is built from the lowercased keyword, so 'Kk' is a duplicate + expect(() => encrypt('Kk', 'ATTACK')).toThrow('Invalid keyword!') +})