Caesar encryption and decryption realization

1. Background and principles

Quoted from Wikipedia

In cryptography, a Caesar cipher (English: Caesar cipher), also known as Caesar Cipher, Caesar conversion on encryption is the simplest and most widely known encryption techniques. It is an alternative to encryption technology, all the letters are in the plaintext back (or forward) offset in the alphabet is replaced after a fixed number in accordance with the ciphertext. For example, when the time offset is 3, all of the letter A will be replaced with D, B becomes E, and so on. The encryption method is Caesar's Roman republic named after allegedly then Caesar had contact with their generals in this way.

 

When the secret key is simply to n, where a character to be encrypted ch, characters after the encryption is ch + n, when more than ch + n 'z', back to the 'a' count.

 

Caesar password encryption, decryption method also through congruence calculation of mathematical methods. First, instead of letters with numbers, A = 0, B = 1 , ..., Z = 25. At this time, the encryption method is the offset of n:

E_{{n}}(x)=(x+n)\mod 26

Decryption is:

D_{{n}}(x)=(x-n)\mod 26

 

2. Encryption

For example

明文:flag{i_LOVE_Reverse}

key=11

 

model = "abcdefghijklmnopqrstuvwxyz"
model2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

str1 = "flag{i_LOVE_Reverse}"
key = 11

for s in str1:
    if s.islower():
        n = model.find(s)
        s = model[n-key]
    elif s.isupper():
        n = model2.find(s)
        s = model2[n - key]
    print(s, end='')
print('\n')

 

 

After the encrypted string obtained:

qwlr{t_WZGP_Cpgpcdp}

 

3. decryption

model = "abcdefghijklmnopqrstuvwxyz"
model2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

str1 = "qwlr{t_WZGP_Cpgpcdp}"

for key in range(1,27):
    print("key=%d"%key, end='\n')
    for s in str1:
        if s.islower():
            n = model.find(s)
            s = model[n-key]
        elif s.isupper():
            n = model2.find(s)
            s = model2[n-key]
        print(s, end='')
    print('\n')

 

key=1
pvkq{s_VYFO_Bofobco}

key=2
oujp{r_UXEN_Anenabn}

key=3
ntio{q_TWDM_Zmdmzam}

key=4
mshn{p_SVCL_Ylclyzl}

key=5
lrgm{o_RUBK_Xkbkxyk}

key=6
kqfl{n_QTAJ_Wjajwxj}

key=7
jpek{m_PSZI_Vizivwi}

key=8
iodj{l_ORYH_Uhyhuvh}

key=9
hnci{k_NQXG_Tgxgtug}

key=10
gmbh{j_MPWF_Sfwfstf}

key=11
flag{i_LOVE_Reverse}

key=12
ekzf{h_KNUD_Qdudqrd}

key=13
djye{g_JMTC_Pctcpqc}

key=14
cixd{f_ILSB_Obsbopb}

= 15, key
bhwc} {eHKRANaranoa

key=16
agvb{d_GJQZ_Mzqzmnz}

key=17
zfua{c_FIPY_Lypylmy}

key=18
yetz{b_EHOX_Kxoxklx}

key=19
xdsy{a_DGNW_Jwnwjkw}

key=20
wcrx{z_CFMV_Ivmvijv}

key = 21
vbqw} {y_BELU_Huluhiu

key=22
uapv{x_ADKT_Gtktght}

key=23
tzou{w_ZCJS_Fsjsfgs}

key=24
synt{v_YBIR_Erirefr}

key=25
rxms{u_XAHQ_Dqhqdeq}

key=26
qwlr{t_WZGP_Cpgpcdp}

 

 

After viewing, we can know, 11 key =, then we decryption is correct string.

 

Guess you like

Origin www.cnblogs.com/Mayfly-nymph/p/11577798.html