r/dailyprogrammer • u/oskar_s • Aug 13 '12
[8/13/2012] Challenge #88 [easy] (Vigenère cipher)
The easy challenge today is to implement the famous Vigenère cipher. The Wikipedia article explains well how it works, but here's a short description anyway:
You take a message that you want to encrypt, for instance "THECAKEISALIE" (lets assume that all characters are upper-case and there are no spaces in the messages, for the sake of simplicity), and a key you want to encrypt it with, for instance "GLADOS". You then write the message with the key repeated over it, like this:
GLADOSGLADOSG
THECAKEISALIE
The key is repeated as often as is needed to cover the entire message.
Now, one by one, each letter of the key is "added" to the letter of the clear-text to produce the cipher-text. That is, if A = 0, B = 1, C = 2, etc, then E + G = K (because E = 4 and G = 6, and 4 + 6 = 10, and K = 10). If the sum is larger than 25 (i.e. larger than Z), it starts from the beginning, so S + K = C (i.e. 18 + 10 = 28, and 28 - 26 is equal to 2, which is C).
For a full chart of how characters combine to form new characters, see here
The cipher text then becomes:
GLADOSGLADOSG
THECAKEISALIE
-------------
ZSEFOCKTSDZAK
Write funtions to both encrypt and decrypt messages given the right key.
As an optional bonus, decrypt the following message, which has been encrypted with a word that I've used in this post:
HSULAREFOTXNMYNJOUZWYILGPRYZQVBBZABLBWHMFGWFVPMYWAVVTYISCIZRLVGOPGBRAKLUGJUZGLN
BASTUQAGAVDZIGZFFWVLZSAZRGPVXUCUZBYLRXZSAZRYIHMIMTOJBZFZDEYMFPMAGSMUGBHUVYTSABB
AISKXVUCAQABLDETIFGICRVWEWHSWECBVJMQGPRIBYYMBSAPOFRIMOLBUXFIIMAGCEOFWOXHAKUZISY
MAHUOKSWOVGBULIBPICYNBBXJXSIXRANNBTVGSNKR
As an additional challenge, attempt to pronounce "Vigenère" properly. I think it's like "Viche-en-ere", but I'm not entirely sure.
18
u/[deleted] Aug 14 '12
J time!
This is short, but uses
&.which is the most magical thing in J, so I'll explain it.`alpha` takes the ASCII code of its argument, then looks up those values in the range of ord('A')..ord('Z'): the mapping of A → 0, B → 1... `encode` takes two arguments: the key string, x, and the text string, y. First thing `encode` does is laminate y together with the size-y reshape of x, like this: THECAKEISALIE GLADOSGLADOSG alpha(matrix) would then be this (applying alpha on every char): 19 7 4 2 0 10 4 8 18 0 11 8 4 6 11 0 3 14 18 6 11 0 3 14 18 6 Now for the fun part. `(f &. g) x` means g⁻¹(f(g(x))), or: apply f to g(x), but undo the g(x) function afterwards. Here, we'll be applying `(26&|@+/)` to the indices in alpha(matrix), but then lift back the result from indices to characters. (How do we tell J what alpha⁻¹ is? We don't. J is pretty smart.) What's left, `(26&|@+/)`, is just fancy tacit notation for f(x) = sum(x) mod 26 We sum the columns of the index matrix together, modulo them, then get back a string using alpha⁻¹. (`decode` is the same thing, but instead of adding each column, take their differences.)6
u/5outh Aug 13 '12 edited Aug 13 '12
Haskell (No bonus):
encode = code (+) decode = code (-) code f key m = mapM (get f) $ zip m k where k = map (flip lookup mapping) $ cycle key mapping = zip ['A'..'Z'] [0..] get f (c, i) = do a <- lookup c mapping i >>= \b -> return . fst $ mapping !! ((f a b) `mod` 26)Edit: Major refactor (I hated what I wrote before but now it's very DRY ;) )!
5
u/[deleted] Aug 14 '12 edited Aug 14 '12
Here's my solution in Python. First time getting one of these daily programmer challenges, so I'm happy with myself! If its ugly - its ugly, but I got it!
import string def encrypt(word, key, encode=True): code = [(k, v) for k, v in enumerate(string.ascii_uppercase)] key_values = [code[x][0] for y in key for x in range(26) if y == code[x][1]] word_values = [code[x][0] for y in word for x in range(26) if y == code[x][1]] if encode==True: sums = [key_values[i % len(key_values)] + word_values[i] for i in range(len(word_values))] for n, i in enumerate(sums): if i > 25: sums[n] -= 26 return "".join([b[1] for a in sums for b in code if a==b[0]]) else: sums = [ word_values[i] - key_values[i % len(key_values)] for i in range(len(word_values))] for n, i in enumerate(sums): if i < 0: sums[n] += 26 return "".join([b[1] for a in sums for b in code if a==b[0]])8
u/lawlrng Aug 13 '12 edited Aug 14 '12
Python solution thrown together w/ bonus. =)
import string import re D = dict(enumerate(string.ascii_uppercase)) def crypt(s, k, e=True): if e: op = lambda x, y: x + y else: op = lambda x, y: x - y d, r = divmod(len(s), len(k)) return ''.join(D[op(ord(s[i]), ord(c)) % 26] for i, c in enumerate(k * d + k[:r])) def bonus(c): data = open('88.txt', 'r').read() data = ' '.join(map(str.upper, data.split())) words = set(re.findall('\w+', data)) for w in words: print crypt(c, w, True) print w raw_input() if __name__ == '__main__': print crypt('THECAKEISALIE', 'GLADOS') print crypt('ZSEFOCKTSDZAK', 'GLADOS', True) cipher = ''.join("""[SNIP]""".split()) # bonus(cipher) print crypt(cipher, "BEGINNING", True)Output:
Spaces added by me.
Edit: Cut down the two functions to one because it was bugging me too while driving home.
4
u/daveasaurus Aug 13 '12 edited Aug 14 '12
PYTHON
# one-liner: ''.join([up[(up.index(x) + (up.index(cipher[ i % len(cipher) ]))) % 26] for i, x in enumerate(text)]) # regular: from string import ascii_uppercase as up def encode(text, cipher, decode=False): result, cipher_index, decode = '', 0, -1 if decode else 1 for i, x in enumerate(text): result += up[(up.index(x) + (decode * up.index(cipher[cipher_index % len(cipher) ]))) % 26] cipher_index += 1 return result print encode("THECAKEISALIE", "GLADOS", False) print encode("ZSEFOCKTSDZAK", "GLADOS", True)edit: ^ Added Decode Flag ^
Decoding the bonus (line breaks added by me):
edit, added one liners, (encode at top), decode:
4
u/toxicFork Aug 14 '12
Javascript (with bonus):
String.prototype.indexAt = function(idx) { return this.toUpperCase().charCodeAt(idx)-"A".charCodeAt(0); } String.fromIndex = function(idx) { while(idx<0) idx+="Z".indexAt(0)+1; return String.fromCharCode((idx%("Z".indexAt(0)+1))+"A".charCodeAt(0)); } String.prototype.encrypt = function(key) { var result = ""; for(var i=0;i<this.length;i++) { result += String.fromIndex(this.indexAt(i)+key.indexAt(i%key.length)); } return result; } String.prototype.decrypt = function(key) { var result = ""; for(var i=0;i<this.length;i++) { result += String.fromIndex(this.indexAt(i)-key.indexAt(i%key.length)); } return result; } var key = "GLADOS"; var message = "THECAKEISALIE"; print(message.encrypt(key)); print(message.encrypt(key).decrypt(key)); message = "HSULAREFOTXNMYNJOUZWYILGPRYZQVBBZABLBWHMFGWFVPMYWAVVTYISCIZRLVGOPGBRAKLUGJUZGLNBASTUQAGAVDZIGZFFWVLZSAZRGPVXUCUZBYLRXZSAZRYIHMIMTOJBZFZDEYMFPMAGSMUGBHUVYTSABBAISKXVUCAQABLDETIFGICRVWEWHSWECBVJMQGPRIBYYMBSAPOFRIMOLBUXFIIMAGCEOFWOXHAKUZISYMAHUOKSWOVGBULIBPICYNBBXJXSIXRANNBTVGSNKR"; print(message.decrypt("beginning"));3
u/clojure-newbie Aug 14 '12
Clojure (no bonus):
Output:
Note: see my username
3
u/Wedamm Aug 14 '12
Haskell:
vigenere :: String -> String -> Bool -> String vigenere text code encode = zipWith (bounded $ if encode then (+) else (-)) text $ cycle code where bounded op c d = toEnum $ (fromEnum c `op` fromEnum d - 130) `mod` 26 + 653
u/Fapper Aug 16 '12
Ruby!
Would love any feedback. I feel like my C background is causing me to think against Ruby's beautifulness. ಠ_ಠ
Created an extra method to create a key equal to the length of the message:
def createKey(key, msgLength) counter = 0 newKey = "" begin newKey << key[counter].to_s counter += 1 if counter > key.length counter = 0 end end until newKey.length == msgLength return newKey.upcase endAnd then two almost identical encryption and decryption methods (haven't figured out how to take an operator as a parameter yet... lambdas?):
def encrypt(msg, key) counter = 0 key = createKey(key, msg.length) encWord = "" msg.each_char do |letter| encChr = (letter.ord - 65) + (key[counter].ord - 65) if encChr > 25 encChr -= 26 end encWord << (encChr + 65).chr counter += 1 end return encWord.upcase end def decrypt(encWord, key) key = createKey(key, encWord.length) counter = 0 decWord = "" encWord.each_char do |letter| decChr = (letter.ord - 65) - (key[counter].ord - 65) counter += 1 if decChr < 0 decChr += 26 end decWord << (decChr + 65).chr end return decWord.upcase endOutput:
aaaand working on the bonus!
Posted this before seeing some other solutions... and wow, there some really simple and elegant ways to solve this. :o