Skip to content

Instantly share code, notes, and snippets.

@adamshaylor
Created June 24, 2022 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamshaylor/2fff8a60b40d2ddb5aed0c24ff8a769f to your computer and use it in GitHub Desktop.
Save adamshaylor/2fff8a60b40d2ddb5aed0c24ff8a769f to your computer and use it in GitHub Desktop.
Caesar cipher demo
/**
* My kid shared his fascination with Caesar ciphers yesterday. He
* challenged me to decrypt one of his messages without the cipher
* offset. I tried to do it by hand, but it was surprisingly difficult
* for his short message. He made me promise not to use frequency
* analysis, but he never said anything about using a computer to brute
* force it!
*/
const validCharacters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] as const;
type ValidCharacters = typeof validCharacters;
type ValidCharacter = ValidCharacters[number];
const offsetCharacter = (inputCharacter: ValidCharacter, offset: number): ValidCharacter => {
const indexOfInput = validCharacters.indexOf(inputCharacter);
const indexOfOffset = (indexOfInput + offset) % validCharacters.length;
return validCharacters[indexOfOffset];
};
const offsetText = (inputText: string, offset: number): string => {
const capitalizedInputText = inputText.toUpperCase();
const characters = capitalizedInputText.split('');
const offsetCharacters = characters.map(character =>
validCharacters.includes(character as ValidCharacter)
? offsetCharacter(character as ValidCharacter, offset)
: character
);
const offsetText = offsetCharacters.join('');
return offsetText;
};
const encryptedText = 'can you understand me';
for (let offset = 0; offset <= validCharacters.length; offset += 1) {
console.log(`${ offset }: ${ offsetText(encryptedText, offset) }`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment