Функция Цезаря Шифра в Python - PullRequest
15 голосов
/ 17 января 2012

Я пытаюсь создать простую функцию Caesar Cipher в Python, которая смещает буквы на основе ввода от пользователя и создает окончательную новую строку в конце.Единственная проблема заключается в том, что в конечном тексте шифра отображается только последний сдвинутый символ, а не вся строка со всеми сдвинутыми символами.

Вот мой код:

plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))

def caesar(plainText, shift): 

    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift 
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
        cipherText = ""
        cipherText += finalLetter

    print "Your ciphertext is: ", cipherText

    return cipherText

caesar(plainText, shift)

Ответы [ 19 ]

1 голос
/ 21 августа 2017
>>> def rotate(txt, key):
...   def cipher(i, low=range(97,123), upper=range(65,91)):
...     if i in low or i in upper:
...       s = 65 if i in upper else 97
...       i = (i - s + key) % 26 + s
...     return chr(i)
...   return ''.join([cipher(ord(s)) for s in txt])

# test
>>> rotate('abc', 2)
'cde'
>>> rotate('xyz', 2)
'zab'
>>> rotate('ab', 26)
'ab'
>>> rotate('Hello, World!', 7)
'Olssv, Dvysk!'
0 голосов
/ 17 января 2019
message = 'The quick brown fox jumped over the lazy dog. 1234567890 !@#$%^&*()_+-'
encrypted = ''.join(chr(ord(char)+3) for char in message)
decrypted = ''.join(chr(ord(char)-3) for char in encrypted)
print(encrypted)
print(decrypted)
# Wkh#txlfn#eurzq#ir{#mxpshg#ryhu#wkh#od}|#grj1#456789:;<3#$C&'(a)-+,b.0
# The quick brown fox jumped over the lazy dog. 1234567890 !@#$%^&*()_+-
0 голосов
/ 12 октября 2017

Почему бы не использовать функцию reverse на входе сдвига, а также присоединить plain_text к сдвигу и ввести его как зашифрованный текст:

Plain = int(input("enter a number ")) 
Rev = plain[::-1]
Cipher = " ".join(for cipher_text in Rev) 
0 голосов
/ 29 сентября 2017

Мне трудно запомнить преобразования char в int, так что это можно оптимизировать

def decryptCaesar(encrypted, shift):
    minRange = ord('a')
    decrypted = ""
    for char in encrypted:
        decrypted += chr(((ord(char) - minRange + shift) % 26) + minRange)

    return decrypted
0 голосов
/ 18 апреля 2017

по мне этот ответ вам пригодится:

def casear(a,key):
str=""
if key>26:
    key%=26
for i in range(0,len(a)):
    if a[i].isalpha():
        b=ord(a[i])
        b+=key
        #if b>90:                   #if upper case letter ppear in your string
        #    c=b-90                 #if upper case letter ppear in your string
        #    str+=chr(64+c)         #if upper case letter ppear in your string
        if b>122:
            c=b-122
            str+=chr(96+c)
        else:
            str+=chr(b)
    else:
        str+=a[i]
print str

a=raw_input()
key=int(input())
casear(a,key)

Эта функция сдвигает все буквы вправо в соответствии с заданной клавишей.

0 голосов
/ 29 марта 2017
import string
wrd=raw_input("Enter word").lower()
fwrd=""
for let in wrd:
    fwrd+=string.ascii_lowercase[(string.ascii_lowercase).index(let)+3]
print"Original word",wrd
print"New word",fwrd
0 голосов
/ 09 ноября 2016
key = 3

def wub():
    def choice():
        choice = input("Do you wish to Encrypt of Decrypt?")
        choice = choice.lower()
        if choice == "e" or "encrypt":
            return choice
        elif choice == "d" or "decrypt":
            return choice
        else:
            print("Invalid response, please try again.")
            choice()

    def message():
        user = input("Enter your message: ")
        return user

    def waffle(choice, message, key):
        translated = ""
        if choice == "e" or "encrypt":
            for character in message:
                num = ord(character)
                num += key
                translated += chr(num)

                derek = open('Encrypted.txt', 'w')
                derek.write(translated)
            derek.close()
            return translated
        else:
            for character in message:
                num = ord(character)
                num -= key
                translated += chr(num)
            return translated

    choice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
    message = message() #Run function for user to enter message. Saves message.
    final = waffle(choice, message, key) #Runs function to translate message, using the choice, message and key variables)
    print("\n Operation complete!")
    print(final)

wub()
0 голосов
/ 17 января 2012
plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))

def caesar(plainText, shift): 
    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift 
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
        #####HERE YOU RESET CIPHERTEXT IN EACH ITERATION#####
        cipherText = ""
        cipherText += finalLetter

    print "Your ciphertext is: ", cipherText

    return cipherText

caesar(plainText, shift)

В качестве еще одного, если ch.isalpha() вы можете поставить finalLetter=ch.

Вы должны удалить строку: cipherText = ""

Приветствия.

0 голосов
/ 08 сентября 2016
from string import ascii_lowercase as alphabet

class CaesarCypher:
    alpha_len = len(alphabet)
    min_guess_rate = 0.2

Шифрование и дешифрование - это одно и то же. если вы хотите расшифровать, например, со сдвигом 10, это означает, что вы можете зашифровать его со сдвигом 26 - 10. В этом случае цикл повторится, если вы собираетесь сдвигать весь алфавит, он будет таким же. Также здесь я продолжаю в верхнем регистре и без символов

    def __call__(self, text, offset, encrypt=True):
        if not encrypt:
            offset = self.alpha_len - offset
        result = []
        for letter in text:
            if not letter.isalpha():
                result.append(letter)
                continue
            letter_to_process = letter.lower()
            processed_letter = self._encrypt_letter(letter_to_process, offset)
            if letter.isupper():
                processed_letter = processed_letter.upper()
            result.append(processed_letter)
        return ''.join(result)

все шифрование идет здесь самое большее.

    def _encrypt_letter(self, letter, offset=0):
        position = (alphabet.find(letter) + offset) % self.alpha_len
        return alphabet[position]

эта часть предназначена для силы брота и угадывает частоту словаря.

    @staticmethod
    def __how_many_do_i_know(text):
        clean_words = filter(lambda x: x.isalpha(), text.split())
        clean_words = ['\'{}\''.format(x) for x in clean_words]
        cursor = conn.cursor()
        query = 'SELECT COUNT(*) FROM mydictionary WHERE word IN ({})'.format(",".join(clean_words))
        cursor.execute(query)
        response = cursor.fetchone()[0]
        return response / len(clean_words)

    def guess_encode(self, text):
        options = [self(text, offset, encrypt=False) for offset in range(self.alpha_len)]
        best_option = [self.__how_many_do_i_know(option) for option in options]
        best_key, guess_rate = max(enumerate(best_option), key=lambda x: x[-1])
        guess_text = options[best_key]
        return best_key, guess_rate, guess_text
...