如何在解密密文的同时找到密钥? (未知密钥)

问题描述 投票:0回答:1

我想在不知道密钥的情况下解密以下经典密文:

Cq ligss’v vcjandd ujw, wuqjwgausjkq cv ulxucdd zrj mhuouahj lbh nuvl upgoqlm rx mhfmllcyw cqxiueuwaiq kbdjyg ghoahh, xlre jhjmrfuo vuws nr fuwaiqsf vwwuwnv. Sm fqvhj nkjydlm ewwrey lfwuwuvahjds vgjkamwawdlyg, ulbhnryldhbb whdtfhk mdxy fggpmhluuwaiq, hlrlyflcqy yywlblblfa ijip ghoahh tuqccqy nushvswwaiqk uqv ghvcfsf uwwrjxv li sjcysnh uiqnyukuwaiqk. Cw hlrncgwm wzy eswntiqw zrj xdlu lfnhyllls dfx fghiaxhfnlsflls, hfmxjcqy nksn rffb ahwwhgwx uwwlhchfnv uuq swfwmv kyqkcwaph vuws uqv nksn ll lheulfm xfwkshjwx gmllfa wjuqkglkmlgh. Fjsslijjuszs qgn rffb kuiwaxslgk cqvcyaxxsfv’ hllnufq vxl uoki xfxhjjlfm jdiesf fggpwlfw, mhuouw wregxfcfsnlghv, shg fuwaiqsf vwwxjcwq, gdccqy cw ahgamswhvsvow cq s qrjfg lbdl lhdchk iq vcjandd nummw.

到目前为止我已经使用了不同的在线工具但没有成功。

我从这个来源中得到启发,使用Pythonic代码达到:

  • 纯文本
  • 寻找钥匙
import argparse

class CaesarAlgorithm:

    def encrypt(self, message, key, alphabet):

        # start with empty ciphertext
        ciphertext = ""

        # iterate through each character in message
        for old_character in message:
            new_character = ""

            # if character is in alphabet -> append to ciphertext
            if(old_character in alphabet):
                index = alphabet.index(old_character)
                new_index = (index + key) % len(alphabet)
                new_character = alphabet[new_index]

            # Note: characters not defined in the alphabet are ignored

            # add new character to ciphertext
            ciphertext = ciphertext + new_character

        # return ciphertext to calling function
        return ciphertext


    def decrypt(self, message, key, alphabet):

        # decrypting is like encrypting but with negative key
        plaintext = self.encrypt(message, 0 - key, alphabet)

        # return plaintext to calling function
        return plaintext


# parse the arguments (args) given via the command line
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--encrypt", dest="encrypt_or_decrypt", action="store_true")
parser.add_argument("-d", "--decrypt", dest="encrypt_or_decrypt", action="store_false")
parser.add_argument("-m", "--message", help="message for encrypt / decrypt", type=str)
parser.add_argument("-k", "--key",     help="key for encrypt / decrypt", type=int)
parser.add_argument("-a", "--alphabet", help="defined alphabet", type=str)


ciphertext="Cq ligss’v vcjandd ujw, wuqjwgausjkq cv ulxucdd zrj mhuouahj lbh nuvl upgoqlm rx mhfmllcyw cqxiueuwaiq kbdjyg ghoahh, xlre jhjmrfuo vuws nr fuwaiqsf vwwuwnv. Sm fqvhj nkjydlm ewwrey lfwuwuvahjds vgjkamwawdlyg, ulbhnryldhbb whdtfhk mdxy fggpmhluuwaiq, hlrlyflcqy yywlblblfa ijip ghoahh tuqccqy nushvswwaiqk uqv ghvcfsf uwwrjxv li sjcysnh uiqnyukuwaiqk. Cw hlrncgwm wzy eswntiqw zrj xdlu lfnhyllls dfx fghiaxhfnlsflls, hfmxjcqy nksn rffb ahwwhgwx uwwlhchfnv uuq swfwmv kyqkcwaph vuws uqv nksn ll lheulfm xfwkshjwx gmllfa wjuqkglkmlgh. Fjsslijjuszs qgn rffb kuiwaxslgk cqvcyaxxsfv’ hllnufq vxl uoki xfxhjjlfm jdiesf fggpwlfw, mhuouw wregxfcfsnlghv, shg fuwaiqsf vwwxjcwq, gdccqy cw ahgamswhvsvow cq s qrjfg lbdl lhdchk iq vcjandd nummw."

# Simulate command-line arguments
# Replace with your desired values
args = parser.parse_args(["-d", "-m", ciphertext, "-k", "3", "-a", "abcdefghijklmnopqrstuvwxyz"])  

# create caesar instance
caesar = CaesarAlgorithm()

# if --encrypt -> call encrypt function
if(args.encrypt_or_decrypt == True):
    print(caesar.encrypt(args.message, args.key, args.alphabet))

# if --decrypt -> call decrypt function
else:
    print(caesar.decrypt(args.message, args.key, args.alphabet))

到目前为止,我无法实现纯文本并找到识别的密钥 即使我尝试使用以下在线工具并手动查找密钥,但我还不能:

python encryption caesar-cipher cryptdecrypt
1个回答
0
投票

您可以编写维吉内雷密码:

class VigenereCipher:
    @staticmethod
    def _key_iter(key):
        while True:
            for ch in key:
                yield ch

    @staticmethod
    def _lookup_table(key, alphabet):
        if any(ch not in alphabet for ch in key):
            raise ValueError("Key should be in the alphabet")
        return {
            ch: alphabet[alphabet.index(ch):] + alphabet[:alphabet.index(ch)]
            for ch in key
        }
        
    @staticmethod
    def encode(message, key, alphabet="abcdefghijklmnopqrstuvwxyz"):
        lookup = VigenereCipher._lookup_table(key, alphabet)
        key_iter = VigenereCipher._key_iter(key)
        return "".join(
            lookup[next(key_iter)][alphabet.index(ch)]
            if ch in alphabet else ch
            for ch in message
        )

    @staticmethod
    def decode(message, key, alphabet="abcdefghijklmnopqrstuvwxyz"):
        lookup = VigenereCipher._lookup_table(key, alphabet)
        key_iter = VigenereCipher._key_iter(key)
        return "".join(
            alphabet[lookup[next(key_iter)].index(ch)]
            if ch in alphabet else ch
            for ch in message
        )

然后,如果您知道密钥(和字母表),则可以解码该字符串:

ciphertext="Cq ligss’v vcjandd ujw, wuqjwgausjkq cv ulxucdd zrj mhuouahj"
print(VigenereCipher.decode(ciphertext.lower(), "uds"))

哪个输出:

in today’s digital age, cryptography is crucial for securing

如果你想找到一把未知的钥匙,那么你必须:

  1. 生成所有可能的按键组合。
  2. 使用密钥解码文本。
  3. 对文本进行某种分析,看看它是否有意义。

例如,如果您知道密钥长度为 3 并且没有重复字符,那么您可以使用以下方法生成潜在的解决方案:

from itertools import permutations

common_two_letter_words = ("as", "to", "be", "in", "by", "is", "it", "at", "of", "or", "on", "an", "us", "if", "my", "do", "no", "he", "up", "so", "am", "me", "go", "hi")
for key in permutations(alphabet, 3):
    output = VigenereCipher.decode(ciphertext.lower(), key)
    if output[:2] in common_two_letter_words and output[9] == "s" and output[37:39] in common_two_letter_words:
        print("".join(key), output)

查看输入是否将两个字母的单词解码为常见单词,以及撇号后面的字符是

s
并输出:

cda an lgdsq’s vagalad sgw, urqhtgyrshhq as ujuuaad xoj keumrafg
cdb an kgdrq’s uagzlac sgv, urphtfyrrhhp as tjutaac xoi ketmrzfg
cde an hgdoq’s ragwlaz sgs, urmhtcyrohhm as qjuqaaz xof keqmrwfg
cdf an ggdnq’s qagvlay sgr, urlhtbyrnhhl as pjupaay xoe kepmrvfg
cdg an fgdmq’s pagulax sgq, urkhtayrmhhk as ojuoaax xod keomrufg
cdh an egdlq’s oagtlaw sgp, urjhtzyrlhhj as njunaaw xoc kenmrtfg
cdi an dgdkq’s nagslav sgo, urihtyyrkhhi as mjumaav xob kemmrsfg
cdj an cgdjq’s magrlau sgn, urhhtxyrjhhh as ljulaau xoa kelmrrfg
cdk an bgdiq’s lagqlat sgm, urghtwyrihhg as kjukaat xoz kekmrqfg
cdl an agdhq’s kagplas sgl, urfhtvyrhhhf as jjujaas xoy kejmrpfg
cdm an zgdgq’s jagolar sgk, urehtuyrghhe as ijuiaar xox keimrofg
cdn an ygdfq’s iagnlaq sgj, urdhttyrfhhd as hjuhaaq xow kehmrnfg
cdo an xgdeq’s hagmlap sgi, urchtsyrehhc as gjugaap xov kegmrmfg
cdp an wgddq’s gagllao sgh, urbhtryrdhhb as fjufaao xou kefmrlfg
cdq an vgdcq’s fagklan sgg, urahtqyrchha as ejueaan xot keemrkfg
cdr an ugdbq’s eagjlam sgf, urzhtpyrbhhz as djudaam xos kedmrjfg
cds an tgdaq’s dagilal sge, uryhtoyrahhy as cjucaal xor kecmrifg
cdt an sgdzq’s caghlak sgd, urxhtnyrzhhx as bjubaak xoq kebmrhfg
cdu an rgdyq’s bagglaj sgc, urwhtmyryhhw as ajuaaaj xop keamrgfg
cdv an qgdxq’s aagflai sgb, urvhtlyrxhhv as zjuzaai xoo kezmrffg
cdw an pgdwq’s zagelah sga, uruhtkyrwhhu as yjuyaah xon keymrefg
cdx an ogdvq’s yagdlag sgz, urthtjyrvhht as xjuxaag xom kexmrdfg
cdy an ngduq’s xagclaf sgy, urshtiyruhhs as wjuwaaf xol kewmrcfg
cdz an mgdtq’s wagblae sgx, urrhthyrthhr as vjuvaae xok kevmrbfg
uda in lodsy’s vigatad agw, crqptggrsphq is uruuiad foj seuurang
udb in kodry’s uigztac agv, crpptfgrrphp is trutiac foi seturzng
udc in jodqy’s tigytab agu, croptegrqpho is srusiab foh sesuryng
ude in hodoy’s rigwtaz ags, crmptcgrophm is qruqiaz fof sequrwng
udf in godny’s qigvtay agr, crlptbgrnphl is prupiay foe sepurvng
udg in fodmy’s pigutax agq, crkptagrmphk is oruoiax fod seourung
udh in eodly’s oigttaw agp, crjptzgrlphj is nruniaw foc senurtng
udi in dodky’s nigstav ago, criptygrkphi is mrumiav fob semursng
udj in codjy’s migrtau agn, crhptxgrjphh is lruliau foa selurrng
udk in bodiy’s ligqtat agm, crgptwgriphg is krukiat foz sekurqng
udl in aodhy’s kigptas agl, crfptvgrhphf is jrujias foy sejurpng
udm in zodgy’s jigotar agk, creptugrgphe is iruiiar fox seiurong
udn in yodfy’s iigntaq agj, crdpttgrfphd is hruhiaq fow sehurnng
udo in xodey’s higmtap agi, crcptsgrephc is grugiap fov segurmng
udp in woddy’s gigltao agh, crbptrgrdphb is frufiao fou sefurlng
udq in vodcy’s figktan agg, craptqgrcpha is erueian fot seeurkng
udr in uodby’s eigjtam agf, crzptpgrbphz is drudiam fos sedurjng
uds in today’s digital age, cryptography is crucial for securing
udt in sodzy’s cightak agd, crxptngrzphx is brubiak foq seburhng
udv in qodxy’s aigftai agb, crvptlgrxphv is zruziai foo sezurfng
udw in podwy’s zigetah aga, cruptkgrwphu is yruyiah fon seyureng
udx in oodvy’s yigdtag agz, crtptjgrvpht is xruxiag fom sexurdng
udy in noduy’s xigctaf agy, crsptigruphs is wruwiaf fol sewurcng
udz in modty’s wigbtae agx, crrpthgrtphr is vruviae fok sevurbng

正确的解决方案就在那里,其他的解决方案都是乱码。通过更多的分析(以及更长单词的字典),您可以将解决方案缩小到正确的键。这留给读者作为练习。

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.