1. 程式人生 > >密碼學程式設計_凱撒加密法

密碼學程式設計_凱撒加密法

import pyperclip
message='This is my secret message.'
key=13
mode='encrypt'
LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated=''
message=message.upper()
for symbol in message:
    if symbol in LETTERS:
        num=LETTERS.find(symbol)
        if mode=='encrypt':
            num=num+key
        elif mode=='decrypt':
            num=num-key
        if num>=len(LETTERS):
            num=num-len(LETTERS)
        elif mode<0:
            num=num+len(LETTERS)
        translated=translated+LETTERS[num]
    else:
        transted=translated+symbol
print(translated)
pyperclip.copy(translated)
    

以上是加密,現在解密:

註釋:mode為encrypt時為加密,為decrypt時則為解密。

import pyperclip
message='GUVFVFZLFRPERGZRFFNTR'
key=13
mode='decrypt'
LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
translated=''
message=message.upper()
for symbol in message:
    if symbol in LETTERS:
        num=LETTERS.find(symbol)
        if mode=='encrypt':
            num=num+key
        elif mode=='decrypt':
            num=num-key
        if num>=len(LETTERS):
            num=num-len(LETTERS)
        elif mode<0:
            num=num+len(LETTERS)
        translated=translated+LETTERS[num]
    else:
        transted=translated+symbol
print(translated)
pyperclip.copy(translated)