Ошибка в пользовательской программе шифрования / дешифрования - PullRequest
0 голосов
/ 26 июня 2018

Я создаю программное обеспечение для шифрования в Python 3.5. Он должен идти вдоль клавиши, используя клавишу [0] для сдвига raw [0], затем клавишу [1] для сдвига raw [1] и т. Д., Возвращаясь к клавише [0], когда raw [i] больше, чем клавиша [i]. % Len (ключ)].

# Converts the key into a numerical list. 
def convert(alph, key):
  for i in range(0, len(key)):
    rem = alph.index(key[i])
    numkey.append(rem)
    print(numkey)
  return numkey

#shifts the text dependant on the key
def encrypt (numkey, raw, alph):
  encr = ""
  emi = ()
  emi = list(emi)
  for i in range (0, len(raw)):
    rem = raw[i]
    rem = alph.index(rem)
    suba = i%len(numkey)
    ram = numkey[suba]
    shift = (rem + ram) % 28  #ensures that shift is an index of alph

    shift = alph[shift]
    emi.append(shift)
  for i in range(0, len(emi)):
    encr = encr + str(emi[i])
  print (encr)

letters = [
    ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 't', 's', 'u', 'v', 'w',
    'x', 'y', 'z', '.', ',', '!', '?']

raw_key = input("Please enter the key:\n")
raw_text = input("Please enter the text you would like to encrypt (no numbers or capitals):")
numkey = convert(letters, raw_key)
encrypt(numkey, raw_text, letters)

Моя проблема связана с программой дешифрования (ниже).

# Converts the key into a numerical list. 
def convert(alph, key):
  numkey = ()
  numkey = list(numkey)  # parse numkey as list
  for i in range(0, len(key)):
    rem = alph.index(key[i])
    numkey.append(rem)
  return numkey

# shifts the text dependant on the key
def encrypt (numkey,raw,alph):
  encr = ""
  emi = ()
  emi = list(emi)
  for i in range (0, len(raw)):
    rem = raw[i]
    rem = alph.index(rem)
    suba = i%len(numkey)
    ram = numkey[suba]
    shift = (rem - ram)

    if shift < 0:
        shift = shift + 28
    else:
        pass        
    shift = alph[shift]
    emi.append(shift)
  for i in range(0, len(emi)):
    encr = encr + str(emi[i])
  print (encr)

letters = [
    ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 't', 's', 'u', 'v', 'w',
    'x', 'y', 'z', '.', ',' ,'!' ,'?']

raw_key = input("Please enter the key:\n")
raw_text = input("Please enter the text you would like to decrypt:\n")
numkey = convert(letters, raw_key)
encrypt(numkey, raw_text, letters)

Почему-то после шифрования символов ",", "?" & "!", если я пропущу их через расшифровку, они всегда возвращаются как "", "a" и "b" соответственно. Это не проблема с любым другим элементом в списке символов.

Если кто-то может определить проблему, я был бы чрезвычайно благодарен.

1 Ответ

0 голосов
/ 27 июня 2018

Проблема здесь в программе шифрования:

shift = (rem + ram) % 28

Длина letters равна 31, а не 28. Здесь вы преждевременно возвращаетесь к началу массива.

Проблема отражена здесь в программе дешифрования:

shift = shift + 28

Есть и другие проблемы. Всего несколько примеров:

  • В программе шифрования numkey не инициализируется в convert()
  • не нужно использовать range(), просто используйте for char in key:
  • нет необходимости в lst = (), за которым следует шаблон lst = list(lst), просто используйте список в первую очередь, lst = []
  • нет проверки на недопустимые символы
  • функция по-прежнему называется encrypt() в программе дешифрования

Вот первый быстрый способ очистки обоих.

Шифрование:

import sys

LETTERS = (
    ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 't', 's', 'u', 'v', 'w',
    'x', 'y', 'z', '.', ',', '!', '?')

# Converts the key into a numerical list.
def convert(alph, key):
  numkey = []
  for char in key:
    if char not in alph:
      sys.exit("Invalid character")
    numkey.append(alph.index(char))
  print(numkey)
  return numkey

# Shifts the text dependant on the key.
def encrypt (numkey, raw, alph):
  encr = ""
  for i, char in enumerate(raw):
    if char not in alph:
      sys.exit("Invalid character")
    rem = alph.index(char)
    ram = numkey[i % len(numkey)]
    # Ensure that shift is an index of alph
    shift = (rem + ram) % len(alph)
    encr = encr + alph[shift]
  print(encr)

raw_key = input("Please enter the key: ")
raw_text = input("Please enter the text you would like to encrypt (no numbers or capitals):\n")

numkey = convert(LETTERS, raw_key)
encrypt(numkey, raw_text, LETTERS)

дешифрование:

import sys

LETTERS = (
    ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 't', 's', 'u', 'v', 'w',
    'x', 'y', 'z', '.', ',' ,'!' ,'?')

# Converts the key into a numerical list.
def convert(alph, key):
  numkey = []
  for char in key:
    if char not in alph:
      sys.exit("Invalid character")
    numkey.append(alph.index(char))
  return numkey

# Shifts the text dependant on the key.
def decrypt(numkey, raw, alph):
  decr = ""
  for i, char in enumerate(raw):
    if char not in alph:
      sys.exit("Invalid character")
    rem = alph.index(char)
    ram = numkey[i % len(numkey)]
    shift = rem - ram
    if shift < 0:
        shift = shift + len(alph)
    decr = decr + alph[shift]
  print(decr)

raw_key = input("Please enter the key: ")
raw_text = input("Please enter the text you would like to decrypt:\n")

numkey = convert(LETTERS, raw_key)
decrypt(numkey, raw_text, LETTERS)
...