ШИФРОВАНИЕ ВИЖИНЕРОМ.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import sqlite3
  2. def create_tables():
  3. conn = sqlite3.connect('alphabets.db')
  4. cursor = conn.cursor()
  5. cursor.execute('''CREATE TABLE IF NOT EXISTS alphabets
  6. (id INTEGER PRIMARY KEY, name TEXT, alphabet TEXT)''')
  7. cursor.execute('''CREATE TABLE IF NOT EXISTS encrypted_texts
  8. (id INTEGER PRIMARY KEY, encrypted_text TEXT)''')
  9. cursor.execute('''INSERT INTO alphabets (name, alphabet) VALUES
  10. ('Полный русский алфавит', 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'),
  11. ('Без буквы ё', 'абвгдежзийклмнопрстуфхцчшщъыьэюя'),
  12. ('С подчеркиванием', 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя_')''')
  13. conn.commit()
  14. conn.close()
  15. def get_custom_alphabet():
  16. length = int(input("Введите длину алфавита: "))
  17. alphabet = input(f"Введите свой алфавит ({length} символов): ")
  18. if len(alphabet) != length:
  19. print("Длина алфавита не соответствует заданной!")
  20. return None
  21. return alphabet
  22. def get_preset_alphabet(choice):
  23. conn = sqlite3.connect('alphabets.db')
  24. cursor = conn.cursor()
  25. cursor.execute('SELECT alphabet FROM alphabets WHERE id=?', (choice,))
  26. alphabet = cursor.fetchone()[0]
  27. conn.close()
  28. return alphabet
  29. def save_encrypted_text(text):
  30. conn = sqlite3.connect('alphabets.db')
  31. cursor = conn.cursor()
  32. cursor.execute('INSERT INTO encrypted_texts (encrypted_text) VALUES (?)', (text,))
  33. conn.commit()
  34. conn.close()
  35. def get_last_encrypted_text():
  36. conn = sqlite3.connect('alphabets.db')
  37. cursor = conn.cursor()
  38. cursor.execute('SELECT encrypted_text FROM encrypted_texts ORDER BY id DESC LIMIT 1')
  39. encrypted_text = cursor.fetchone()[0]
  40. conn.close()
  41. return encrypted_text
  42. def vigenere_encrypt(plaintext, key, alphabet):
  43. encrypted = ''
  44. alphabet_len = len(alphabet)
  45. key_indices = [alphabet.index(char) for char in key]
  46. for i, char in enumerate(plaintext):
  47. if char in alphabet:
  48. plain_idx = alphabet.index(char)
  49. key_idx = key_indices[i % len(key)]
  50. encrypted += alphabet[(plain_idx + key_idx) % alphabet_len]
  51. else:
  52. encrypted += char
  53. return encrypted
  54. def vigenere_decrypt(ciphertext, key, alphabet):
  55. decrypted = ''
  56. alphabet_len = len(alphabet)
  57. key_indices = [alphabet.index(char) for char in key]
  58. for i, char in enumerate(ciphertext):
  59. if char in alphabet:
  60. cipher_idx = alphabet.index(char)
  61. key_idx = key_indices[i % len(key)]
  62. decrypted += alphabet[(cipher_idx - key_idx) % alphabet_len]
  63. else:
  64. decrypted += char
  65. return decrypted
  66. def main():
  67. create_tables()
  68. choice = int(input("Введите 1 для своего алфавита, 2 для заготовленного: "))
  69. if choice == 1:
  70. alphabet = get_custom_alphabet()
  71. else:
  72. preset_choice = int(input("Выберите заготовленный алфавит (1 полный Рсский алфавит без ё, 2 с ё, или 3 с _ в конце ): "))
  73. alphabet = get_preset_alphabet(preset_choice)
  74. if not alphabet:
  75. print("Ошибка с алфавитом!")
  76. return
  77. print(f"Ваш алфавит: {alphabet}")
  78. while True:
  79. action = input("Введите 'шифр' для шифрования, 'дешифр' для расшифрования, 'exit' для выхода: ")
  80. if action == 'шифр':
  81. key = input("Введите ключ: ")
  82. plaintext = input("Введите текст для шифрования: ")
  83. encrypted_text = vigenere_encrypt(plaintext, key, alphabet)
  84. print(f"Зашифрованный текст: {encrypted_text}")
  85. save_encrypted_text(encrypted_text)
  86. elif action == 'дешифр':
  87. key = input("Введите ключ: ")
  88. ciphertext = get_last_encrypted_text()
  89. decrypted_text = vigenere_decrypt(ciphertext, key, alphabet)
  90. print(f"Расшифрованный текст: {decrypted_text}")
  91. elif action == 'exit':
  92. print("Программа завершена.")
  93. break
  94. else:
  95. print("Неверная команда, попробуйте снова.")
  96. if __name__ == '__main__':
  97. main()