Vigenère Cipher
InterviewTime limit1sMemory limit128 MB
Encrypt each given plaintext with the Vigenère cipher, shifting every letter by the aligned repeated keyword letter modulo 26.
- Level
Easy2 of 10
- Topics
- String, Implementation, Math
- Solved
- No attempts yet
Problem
Black Widow and Hawkeye need to plan a surprise birthday party for Nick Fury, and they decide to encrypt their messages so Nick can't read them. They use the Vigenère cipher, a simple form of polyalphabetic substitution first described by Giovan Battista Bellaso in 1553.
The Vigenère cipher generalizes the Caesar cipher. In a Caesar cipher, every letter is shifted by the same fixed amount; for example, with a shift of 3, A becomes D, B becomes E, and Y becomes B (wrapping around the end of the alphabet). The Vigenère cipher instead applies a sequence of Caesar ciphers with different shift amounts.
To encrypt, the sender picks a keyword and repeats it until it is as long as the plaintext. For plaintext ATTACKATDAWN and keyword LEMON, the repeated key is:
Plaintext: ATTACKATDAWN
Keyword: LEMONLEMONLE
Each plaintext letter is shifted by the amount given by the aligned keyword letter, where a letter's shift is its position in the alphabet (A = 0, B = 1, …, Z = 25). So a keyword letter L shifts by 11: A becomes L, B becomes M, and after Z the alphabet wraps back to A. A keyword letter E shifts by 4, so T becomes X.
Formally, let the plaintext letters be and the repeated keyword letters be ; then each ciphertext letter is , using the alphabet positions above.
Following this rule, ATTACKATDAWN under keyword LEMON encrypts to LXFOPVEFRNHR.
Write a program that encrypts messages with the Vigenère cipher.
Input
The first line contains the number of test cases ().
Each of the next lines contains one test case: a keyword and a plaintext, separated by a single space. Both strings consist only of uppercase letters A–Z (any digits, punctuation, and whitespace have already been stripped out).
Output
For each test case, print one line in the form:
Ciphertext: <encrypted text>
where <encrypted text> is the plaintext encrypted with the given keyword using the Vigenère cipher.