# [Crypto] Valentine's Day {%hackmd M1bgOPoiQbmM0JRHWaYA1g %} > -👤堇姬 ## Step.1 我們知這個題目是Affine cipher ``` Solve this code before opening the box for me~♡ cipher text: hphxhHYK{fkknsj_h1um3w_hfs_xqtaj_gd_jdj5} Dtz wjhjnaji hmthtqfyjx mfsirfij gd dtzw lnwqkwnjsi ``` ## Step.2 根據Affine cipher解密的方法 **$P \equiv keya^{-1}(C-keyb)\pmod {26}$** 因為這題有給keya,那只要暴力破解keyb(1~25)即可。 **Solve Script :** ```python def multiplicative_inverse(a, m): for x in range(1, m): if (a * x) % m == 1: return x def affine_decrypt(cipher_text, a, b): decrypted_text = "" a_inverse = multiplicative_inverse(a, 26) for char in cipher_text: if char.isalpha(): if char.isupper(): decrypted_char = chr(((a_inverse * (ord(char) - ord('A') - b)) % 26) + ord('A')) else: decrypted_char = chr(((a_inverse * (ord(char) - ord('a') - b)) % 26) + ord('a')) decrypted_text += decrypted_char else: decrypted_text += char return decrypted_text a = 646458645 cipher_text="hphxhHYK{fkknsj_h1um3w_hfs_xqtaj_gd_jdj5} Dtz wjhjnaji hmthtqfyjx mfsirfij gd dtzw lnwqkwnjsi" for b in range(1,26): decrypted_text = affine_decrypt(cipher_text, a, b) print("keyB={},明文".format(b), decrypted_text) ``` ## Another way 其實你會發現keya=1,所以其實他是一題凱薩密碼,直接推偏移量或是暴力破解即可。 ~~至於為啥他會變凱薩密碼,是因為出題者隨便打了一串keya然後沒有驗www~~