|
| 1 | +// Нужно написать 2 функции: |
| 2 | +// 1. Шифратор пароля - функция принимает пароль, разбивает по символам, меняет местами какие-то буквы по заданному алгоритму и возвращает строку. |
| 3 | +// 2. Проверка пароля - принимает зашифрованный пароль и второй пароль. Воспроизводит алгоритм назад на зашифрованном пароле и возвращает "true", если он совпадает со втором паролем и "false", если нет. |
| 4 | +// Результат должен быть следующим: |
| 5 | +// crypto(‘password’) -> ssapdorw |
| 6 | +// check(‘ssapdorw’, ‘password’) -> true |
| 7 | +// check(‘ssapdorw’, ‘wrong’) -> false |
| 8 | + |
| 9 | +const passwordToEncrypt = 'password'; |
| 10 | +const wrongPassword = 'wrong'; |
| 11 | + |
| 12 | +function crypto(password) { |
| 13 | + if (!password || password.trim() === '') { |
| 14 | + return false; |
| 15 | + } |
| 16 | + |
| 17 | + const middleIndex = Math.floor(password.length / 2); |
| 18 | + const firstPart = password.slice(0, middleIndex); |
| 19 | + const secondPart = password.slice(middleIndex); |
| 20 | + |
| 21 | + // 1. Переворачиваем первую часть |
| 22 | + const encryptedFirstPart = firstPart.split('').reverse().join(''); |
| 23 | + |
| 24 | + // 2. Во второй части меняем местами первый и последний символы |
| 25 | + let encryptedSecondPart; |
| 26 | + if (secondPart.length > 1) { |
| 27 | + const firstLetter = secondPart[0]; |
| 28 | + const lastLetter = secondPart[secondPart.length - 1]; |
| 29 | + const middlePart = secondPart.slice(1, -1); |
| 30 | + encryptedSecondPart = lastLetter + middlePart + firstLetter; |
| 31 | + } else { |
| 32 | + // Если вторая часть состоит из одного символа или пуста, оставляем как есть |
| 33 | + encryptedSecondPart = secondPart; |
| 34 | + } |
| 35 | + |
| 36 | + return encryptedFirstPart + encryptedSecondPart; |
| 37 | +} |
| 38 | + |
| 39 | +function check(encryptedPassword, originalPassword) { |
| 40 | + // Самый надежный способ проверки - зашифровать оригинальный пароль и сравнить результат с уже зашифрованным. |
| 41 | + if (!originalPassword || !encryptedPassword) { |
| 42 | + return false; |
| 43 | + } |
| 44 | + return crypto(originalPassword) === encryptedPassword; |
| 45 | +} |
| 46 | + |
| 47 | +// Шифруем пароль 'password' |
| 48 | +const encrypted = crypto(passwordToEncrypt); |
| 49 | +console.log(encrypted); // ssapdorw |
| 50 | + |
| 51 | +// Проверяем правильный пароль |
| 52 | +const isCorrect = check(encrypted, passwordToEncrypt); |
| 53 | +console.log(isCorrect); // true |
| 54 | + |
| 55 | +// Проверяем неправильный пароль |
| 56 | +const isWrong = check(encrypted, wrongPassword); |
| 57 | +console.log(isWrong); // false |
0 commit comments