[Codewars] 098: Vigenère Cipher Helper

題目

The Vigenère cipher is a classic cipher originally developed by Italian cryptographer Giovan Battista Bellaso and published in 1553. It is named after a later French cryptographer Blaise de Vigenère, who had developed a stronger autokey cipher (a cipher that incorporates the message of the text into the key).

The cipher is easy to understand and implement, but survived three centuries of attempts to break it, earning it the nickname "le chiffre indéchiffrable" or "the indecipherable cipher."

From Wikipedia:

The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution.

. . .

In a Caesar cipher, each letter of the alphabet is shifted along some number of places; for example, in a Caesar cipher of shift 3, A would become D, B would become E, Y would become B and so on. The Vigenère cipher consists of several Caesar ciphers in sequence with different shift values.

Assume the key is repeated for the length of the text, character by character. Note that some implementations repeat the key over characters only if they are part of the alphabet -- this is not the case here.

The shift is derived by applying a Caesar shift to a character with the corresponding index of the key in the alphabet.

Visual representation:

"my secret code i want to secure"  // message
"passwordpasswordpasswordpasswor"  // key

Write a class that, when given a key and an alphabet, can be used to encode and decode from the cipher.

Example

var alphabet = 'abcdefghijklmnopqrstuvwxyz';
var key = 'password';

// creates a cipher helper with each letter substituted
// by the corresponding character in the key
var c = new VigenèreCipher(key, alphabet);

c.encode('codewars'); // returns 'rovwsoiv'
c.decode('laxxhsj');  // returns 'waffles'

Any character not in the alphabet must be left as is. For example (following from above):

c.encode('CODEWARS'); // returns 'CODEWARS'

維吉尼亞密碼的加密和解密程序

我的答案

# coding: utf-8
class VigenereCipher(object):
    def __init__(self, key, alphabet):
        self.key = key
        self.n = len(key)
        self.N = len(alphabet)
        self.dic1 = dict(zip(alphabet, list(range(self.N))))
        self.dic2 = dict(zip(list(range(self.N)), alphabet))
    
    def encode(self, text):
        if self.N == 0 or self.n == 0:
            return text
        else:
            res = ''
            text = text
            for i in range(len(text)):
                if text[i] in self.dic1:
                    shift = self.dic1[self.key[i%self.n]]
                    res += self.dic2[(self.dic1[text[i]] + shift) % self.N]
                else:
                    res += text[i]
            return res
    
    def decode(self, text):
        if self.N == 0 or self.n == 0:
            return text
        else:
            res = ''
            text = text
            for i in range(len(text)):
                if text[i] in self.dic1:
                    shift = self.dic1[self.key[i%self.n]]
                    res += self.dic2[(self.dic1[text[i]] - shift + self.N) % self.N]
                else:
                    res += text[i]
            return res

我的答案

from itertools import cycle

class VigenereCipher (object):
    def __init__(self, key, alphabet):
        self.key = key.decode('utf-8')
        self.alphabet = alphabet.decode('utf-8')
    
    def cipher(self, mode, str):
        return ''.join(self.alphabet[(self.alphabet.index(m) +
                  mode * self.alphabet.index(k)) % len(self.alphabet)]
                  if m in self.alphabet else m for m, k in zip(str.decode('utf-8'),
                  cycle(self.key))).encode('utf-8')
    
    def encode(self, str): return self.cipher(1, str)
    def decode(self, str): return self.cipher(-1, str)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末祟同,一起剝皮案震驚了整個濱河市楣导,隨后出現(xiàn)的幾起案子勇蝙,更是在濱河造成了極大的恐慌耽梅,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件叉橱,死亡現(xiàn)場離奇詭異挫以,居然都是意外死亡,警方通過查閱死者的電腦和手機窃祝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進店門掐松,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人粪小,你說我怎么就攤上這事大磺。” “怎么了探膊?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵杠愧,是天一觀的道長。 經(jīng)常有香客問我逞壁,道長流济,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任腌闯,我火速辦了婚禮绳瘟,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘姿骏。我一直安慰自己糖声,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布分瘦。 她就那樣靜靜地躺著蘸泻,像睡著了一般。 火紅的嫁衣襯著肌膚如雪擅腰。 梳的紋絲不亂的頭發(fā)上蟋恬,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天翁潘,我揣著相機與錄音趁冈,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛渗勘,可吹牛的內(nèi)容都是我干的沐绒。 我是一名探鬼主播,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼旺坠,長吁一口氣:“原來是場噩夢啊……” “哼乔遮!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起取刃,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤蹋肮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后璧疗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體坯辩,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年崩侠,在試婚紗的時候發(fā)現(xiàn)自己被綠了漆魔。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡却音,死狀恐怖改抡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情系瓢,我是刑警寧澤阿纤,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站夷陋,受9級特大地震影響阵赠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜肌稻,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一清蚀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧爹谭,春花似錦枷邪、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至腹泌,卻和暖如春嘶卧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背凉袱。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工芥吟, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留侦铜,地道東北人。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓钟鸵,卻偏偏與公主長得像钉稍,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子棺耍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,464評論 0 13
  • by Lene Nielsen The persona method has developed from bei...
    鮮核桃閱讀 1,083評論 0 0
  • (一) 我的房子兩平方 只能容納孤獨的床 和小小的窗 床穩(wěn)住了身子 窗動了心 我不需要門 因為思想 可以乘著詩贡未,飛...
    Iday閱讀 461評論 0 0
  • 傷口是光進入你內(nèi)心的地方。 你正在尋找的東西也在尋找你蒙袍。 你今生的任務(wù)不是去尋找愛俊卤, 只是尋找并發(fā)現(xiàn), 你內(nèi)心構(gòu)筑...
    萌萌心理咨詢師閱讀 441評論 0 1
  • “關(guān)于品味哺哼,如果真要學(xué),那么該學(xué)的東西可多著了叼风!一個人會不會品味人生取董,關(guān)系著能不能過有風(fēng)格的生活。 懂得品味无宿、認(rèn)真...
    f72248ce4552閱讀 556評論 1 3