[英]How would I reverse this? Python 3.8
因此,我使用 python 創建了一個非常……奇怪的小凱撒密碼。 很簡單。 除了,我真的不是很擅長數學,我想知道我該如何扭轉這一點?
def encrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
if (char.isupper()):
result += chr((ord(char) + s - 23+213**3) % 26 + 713)
else:
result += chr((ord(char) + s - 23+213**3) % 26 + 715)
return result
text = input("Message: ")
s = 964
print ("Text: " + text)
print ("Shift: " + str(s))
print ("Cipher: " + encrypt(text,s))
任何形式的幫助將不勝感激。
編輯:
我很接近:我對輪班的工作方式進行了數學計算:
如果字母是大寫字母: 1. 964 - 23+213^3, which ends up as -9662656
2. Get the remainder of that divided by 26 (modulo operator) -9662656 % 26 = 10
3. 10 + 714 = 724
4. 724-63
我通過反復試驗得到了 63...
唯一的問題,直到字母 M 為止,這一切都有效。在這種情況下,最后 13 個字母向后移動 26 個字符? 我將如何解決這個問題?
def decrypt(text,s):
result = ""
for i in range(len(text)):
char = text[i]
result += chr((ord(char) - s))
return result
text = input("Message: ")
s = 724-63
print ("Text: " + text)
print ("Shift: " + str(s))
print ("Cipher: " + decrypt(text,s))
Text: ˖˗˘˙˚˛˜˝˞˟ˠˡˢˉˊˋˌˍˎˏːˑ˒˓˔˕
Shift: 661
Cipher: ABCDEFGHIJKLM456789:;<=>?@
我重寫了您的加密 function 以顯示計算的單個部分。 然后我寫了解密 function 來展示如何“撤消”它們。
請注意,在使用 mod 26 時,-23+213 3等價於 24。
def encrypt(text, s):
cipher = ""
for pt_char in text:
val = ord(pt_char) # 65 <= val < 91
t0 = val % 26 # 0 <= t0 < 26, with A=>13, B=>14, ... N=>0 etc.
t1 = (t0 + s + 24) % 26 # 0 <= t1 < 26
t2 = t1 + 715 # 715 <= t2 < 741
cipher += chr(t2)
return cipher
def decrypt(ct, s):
plain = ""
for ct_char in ct:
t2 = ord(ct_char) # 715 <= t2 < 741
t1 = t2 - 715 # 0 <= t1 < 26
t0 = (t1 - s - 24 + 13) % 26 # 0 <= t0 < 26
val = t0 + 65 # 65 <= val < 91
plain += chr(val)
return plain
同樣,這僅適用於大寫 ASCII 字母。 注意評論,他們在告訴你一些事情。
這里有一些簡短的單行代碼,只是為了向您展示有關生成器如何生成緊湊代碼的一些信息。
def encrypt_one_liner(text, s):
return ''.join(chr((ord(x) + s + 24) % 26 + 715) for x in text)
def decrypt_one_liner(text, s):
return ''.join(chr((ord(x) + 2 - s) % 26 + 65) for x in text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.