From ad1078836c4744aca1e29112bf6b8420f46f15d6 Mon Sep 17 00:00:00 2001 From: AnnaEf24 <44416169+AnnaEf24@users.noreply.github.com> Date: Mon, 2 May 2022 15:29:51 +0300 Subject: [PATCH 1/2] WebEncryption added --- encryption/alphabet.py | 7 +++ encryption/caesar_an.py | 70 +++++++++++++++++++++++ encryption/caesar_ciph.py | 59 +++++++++++++++++++ encryption/encryption.py | 35 ++++++++++++ encryption/file.txt | 4 ++ encryption/main.py | 9 +++ encryption/vernam_ciph.py | 25 +++++++++ encryption/vigenere_ciph.py | 109 ++++++++++++++++++++++++++++++++++++ 8 files changed, 318 insertions(+) create mode 100644 encryption/alphabet.py create mode 100644 encryption/caesar_an.py create mode 100644 encryption/caesar_ciph.py create mode 100644 encryption/encryption.py create mode 100644 encryption/file.txt create mode 100644 encryption/main.py create mode 100644 encryption/vernam_ciph.py create mode 100644 encryption/vigenere_ciph.py diff --git a/encryption/alphabet.py b/encryption/alphabet.py new file mode 100644 index 0000000..4b0677b --- /dev/null +++ b/encryption/alphabet.py @@ -0,0 +1,7 @@ +#alphabets +alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ' +alphabet_vig = 'ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ > len(alphabet_RU): + enru = True + for i in text: + if i == ' ': + space += 1 + elif i in alpha: + rate[ord_alpha[i]] += 1 + rate = list(map(lambda x: x / (len(text) - space), rate)) + shifts = {i : 0 for i in range(len(ord_alpha))} + for i in range(len(ord_alpha)): + diff = 1 + sdv = 0 + for p in range(len(ord_alpha)): + if diff > abs(rate[i] - rate_al[p]): + if (enru == False) or (enru and ((i < 26 and p < 26) or (i > 25 and p > 25))): + diff = abs(rate[i] - rate_al[p]) + sdv = p + if i > sdv: + sdv = i - sdv + elif i < sdv: + sdv = len(alpha) - sdv + i + shifts[sdv] += 1 + + shift = sorted(list(shifts.keys()), key=lambda x: shifts[x])[-1] + return shift + + + + +def caesar_analysis(input_file, lang): + with open(input_file, 'r') as f: + text = f.read().upper() + + if lang == "BOTH": + alpha = alphabet + rate_al = rate_BOTH + if lang == "RU": + alpha=alphabet_RU + rate_al = rate_RU + if lang == "EU": + alpha=alphabet_EU + rate_al = rate_EU + ord_alpha = {} + for i in range(len(alpha)): + ord_alpha[alpha[i]] = i + + shift = find_shift(text, ord_alpha, rate_al, alpha) + result = '' + for i in text: + place = alpha.find(i) + new_place = (place - shift) % len(alpha) + if i in alphabet: + result += alpha[new_place] + else: + result += i + + print('Decipher:', result) + print('Input text: ', text) + res = open('Caesar_decoding.txt', 'w') + res.write(result) diff --git a/encryption/caesar_ciph.py b/encryption/caesar_ciph.py new file mode 100644 index 0000000..8d6b326 --- /dev/null +++ b/encryption/caesar_ciph.py @@ -0,0 +1,59 @@ +from alphabet import * + +def caesar_cipher(input_file, lang, key): + with open(input_file, 'r', encoding = 'utf-8') as f: + text = f.read().upper() + #key of encryption + shift = int(key) + keyf = open('Caesar_key.txt', 'w') + keyf.write(str(shift)) + result = '' + alpha = '' + if lang == "BOTH": + alpha=alphabet + if lang == "RU": + alpha=alphabet_RU + if lang == "EU": + alpha=alphabet_EU + + for i in text: + place = alpha.find(i) + new_place = (place + shift) % len(alpha) + if i in alphabet: + result += alpha[new_place] + else: + result += i + + #print('Cipher:', result) + #print('Input text: ', text) + res = open('Caesar_encryption.txt', 'w') + res.write(result) + return 'Cipher:', result + +def caesar_decipher(input_file, lang, key): + with open(input_file, 'r') as f: + text = f.read().upper() + result = '' + alpha = '' + if lang == "BOTH": + alpha=alphabet + if lang == "RU": + alpha=alphabet_RU + if lang == "EU": + alpha=alphabet_EU + shift = int(key) + + for i in text: + place = alpha.find(i) + new_place = (place - shift) % len(alpha) + if i in alphabet: + result += alpha[new_place] + else: + result += i + + #print('Decipher:', result) + #print('Input text: ', text) + res = open('Caesar_decoding.txt', 'w') + res.write(result) + return 'Decipher:', result + diff --git a/encryption/encryption.py b/encryption/encryption.py new file mode 100644 index 0000000..b17d479 --- /dev/null +++ b/encryption/encryption.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import os +import random +import click +import caesar_ciph +import vigenere_ciph +import vernam_ciph +import caesar_an + +def encrypt(cipher, input_file, lang, key): + if cipher == 'Caesar_cipher' or cipher == 'cac': + result = caesar_ciph.caesar_cipher(input_file, lang, key) + if cipher == 'Caesar_decipher' or cipher == 'cad': + result = caesar_ciph.caesar_decipher(input_file, lang, key) + if cipher == 'Vigenere_cipher' or cipher == 'vic': + result = vigenere_ciph.vigenere_cipher(input_file, lang, key) + if cipher == 'Vigenere_decipher' or cipher == 'vid': + result = vigenere_ciph.vigenere_decipher(input_file, lang, key) + if cipher == 'Vernam_cipher' or cipher == 'vec': + result = vernam_ciph.vernam_cipher(input_file) + with open('Vernam_encryption.txt', 'r', encoding = 'Latin-1') as file: + result = 'Cipher: ' + file.read() + '''with open(input_file, 'r', encoding = 'utf-8') as file: + print('Input_text: ', file.read())''' + if cipher == 'Vernam_decipher' or cipher == 'ved': + vernam_ciph.vernam_decipher(input_file, key) + with open('Vernam_decoding.txt', 'r', encoding = 'utf-8') as file: + result = 'Decipher: ' + file.read() + '''with open(input_file, 'r', encoding = 'Latin-1') as file: + print('Input_text: ', file.read())''' + if cipher == 'Caesar_analysis' or cipher == 'can': + result = caesar_an.caesar_analysis(input_file, lang) + return result diff --git a/encryption/file.txt b/encryption/file.txt new file mode 100644 index 0000000..f473b20 --- /dev/null +++ b/encryption/file.txt @@ -0,0 +1,4 @@ +Князь Василий говорил всегда лениво, как актер говорит роль старой пиесы. Анна Павловна Шерер, напротив, несмотря на свои сорок лет, была преисполнена оживления и порывов. +Быть энтузиасткой сделалось ее общественным положением, и иногда, когда ей даже того не хотелось, она, чтобы не обмануть ожиданий людей, знавших ее, делалась энтузиасткой. Сдержанная улыбка, игравшая постоянно на лице Анны Павловны, хотя и не шла к ее отжившим чертам, выражала, как у избалованных детей, постоянное сознание своего милого недостатка, от которого она не хочет, не может и не находит нужным исправляться. +В середине разговора про политические действия Анна Павловна разгорячилась. +— Ах, не говорите мне про Австрию! Я ничего не понимаю, может быть, но Австрия никогда не хотела и не хочет войны. Она предает нас. Россия одна должна быть спасительницей Европы. Наш благодетель знает свое высокое призвание и будет верен ему. Вот одно, во что я верю. Нашему доброму и чудному государю предстоит величайшая роль в мире, и он так добродетелен и хорош, что Бог не оставит его, и он исполнит свое призвание задавить гидру революции, которая теперь еще ужаснее в лице этого убийцы и злодея. Мы одни должны искупить кровь праведника. На кого нам надеяться, я вас спрашиваю.. Англия с своим коммерческим духом не поймет и не может понять всю высоту души императора Александра. Она отказалась очистить Мальту. Она хочет видеть, ищет заднюю мысль наших действий. Что они сказали Новосильцеву Ничего. Они не поняли, они не могли понять самоотвержения нашего императора, который ничего не хочет для себя и все хочет для блага мира. И что они обещали Ничего. И что обещали, и того не будет! Пруссия уже объявила, что Бонапарте непобедим и что вся Европа ничего не может против него.. \ No newline at end of file diff --git a/encryption/main.py b/encryption/main.py new file mode 100644 index 0000000..cfb7ba5 --- /dev/null +++ b/encryption/main.py @@ -0,0 +1,9 @@ +import uvicorn +from fastapi import FastAPI, File, UploadFile +from encryption import encrypt + +app = FastAPI() + +@app.post("/") +async def api_data(input_file: UploadFile, cipher: str, language: str, key: str): + return encrypt(cipher, input_file.filename, language, key) diff --git a/encryption/vernam_ciph.py b/encryption/vernam_ciph.py new file mode 100644 index 0000000..dab49cb --- /dev/null +++ b/encryption/vernam_ciph.py @@ -0,0 +1,25 @@ +import random +from alphabet import * + +def vernam_cipher(input_file): + with open(input_file, 'rb') as inf: + keyf = open('Vernam_key.txt', 'wb') + outf = open('Vernam_encryption.txt', 'wb') + byte_in = inf.read(1) + while byte_in: + new_key = random.randint(0, 255) + new_byte = bytes([ord(byte_in) ^ new_key]) + outf.write(new_byte) + keyf.write(bytes([new_key])) + byte_in = inf.read(1) + +def vernam_decipher(input_file, key): + with open(input_file, 'rb') as inf: + keyf = open(key, 'rb') + outf = open('Vernam_decoding.txt', 'wb') + byte_in = inf.read(1) + while byte_in: + new_key = keyf.read(1) + new_byte = bytes([ord(new_key) ^ ord(byte_in)]) + outf.write(new_byte) + byte_in = inf.read(1) diff --git a/encryption/vigenere_ciph.py b/encryption/vigenere_ciph.py new file mode 100644 index 0000000..83550c4 --- /dev/null +++ b/encryption/vigenere_ciph.py @@ -0,0 +1,109 @@ +from alphabet import * + +def form_dict(lang): + d = {} + iter = 0 + + alphab = '' + if lang == "BOTH": + alphab = alphabet_vig + if lang == "RU": + alphab = alphabet_vigru + if lang == "EU": + alphab = alphabet_vigeu + + for i in alphab: + d[iter] = i + iter = iter + 1 + return d + +def encode_val(word, lang): + list_code = [] + lent = len(word) + d = form_dict(lang) + + for w in range(lent): + for value in d: + if word[w] == d[value]: + list_code.append(value) + return list_code + +def comparator(value, key): + len_key = len(key) + dic = {} + iter = 0 + full = 0 + + for i in value: + dic[full] = [i,key[iter]] + full = full + 1 + iter = iter +1 + if (iter >= len_key): + iter = 0 + return dic + +def full_encode(value, key, lang): + dic = comparator(value, key) + lis = [] + d = form_dict(lang) + + for v in dic: + go = (dic[v][0]+dic[v][1]) % len(d) + lis.append(go) + return lis + +def decode_val(list_in, lang): + list_code = [] + lent = len(list_in) + d = form_dict(lang) + count=0 + for i in range(lent): + for value in d: + if list_in[i] == value: + list_code.append(d[value]) + return list_code + +def full_decode(value, key, lang): + dic = comparator(value, key) + d = form_dict(lang) + lis =[] + + for v in dic: + go = (dic[v][0]-dic[v][1]+len(d)) % len(d) + lis.append(go) + return lis + +def vigenere_cipher(input_file, lang, key): + with open(input_file, 'r', encoding = 'utf-8') as f: + text = f.read().upper() + keyf = open('Vigenere_key.txt', 'w') + keyf.write(key) + key_encoded = encode_val(key.upper(), lang) + value_encoded = encode_val(text, lang) + shifre = full_encode(value_encoded, key_encoded, lang) + result = decode_val(shifre, lang) + decoded = full_decode(shifre, key_encoded, lang) + + res = open('Vigenere_encryption.txt', 'w') + res.write(''.join(result)) + + #in case you wanted to explore the process: + #print ('Value: ', value_encoded) + #print ('Key: ', key_encoded) + #print ('Decode list:', decoded) + #print ('Cipher: ', ''.join(result)) + #print ('Input text: ', text) + return 'Cipher:', ''.join(result) + +def vigenere_decipher(input_file, lang, key): + with open(input_file, 'r') as f: + text = f.read() + key_encoded = encode_val(key.upper(), lang) + shifre = encode_val(text, lang) + decoded = full_decode(shifre, key_encoded, lang) + result = ''.join(decode_val(decoded, lang)) + res = open('Vigenere_decoding.txt', 'w') + res.write(''.join(result)) + #print ('Dechipher: ', result) + #print ('Input text: ', text) + return 'Decipher:', ''.join(result) From 3797f41700144c3b1f6b73cac28baef003c5bc8b Mon Sep 17 00:00:00 2001 From: Annarrchy <91114932+Annarrchy@users.noreply.github.com> Date: Mon, 2 May 2022 15:46:46 +0300 Subject: [PATCH 2/2] Update README.md --- README.md | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e6e4078..a1f1d0d 100644 --- a/README.md +++ b/README.md @@ -1 +1,18 @@ -# Python-Efimova-121 \ No newline at end of file +# Веб версия шифровальщика +## Прочитать о непосредствнной работе программы можно, перейдя на ветку Project в файл README.md +## Реализация и запуск +Реализовано с помощью FastAPI +#### Необходимы библиотеки: FastAPI, uvicorn, python-multipart +Запуск производится в командной строке из папки encryption с помощью команды: +``` +$ python -m uvicorn main:app --reload +``` +После необходимо перейи по возникшей ссылке и дописать в конце "/docs" + +В появившемся окне надо нажать кнопку "Try it out", после чего вбить данные в 3 графы: ++ режим работы (Один из: Caesar_cipher (или cac), Caesar_decipher (cad), Vigenere_cipher (vic), Vigenere_decipher (vid), Vernam_cipher (vec), Vernam_decipher (ved), Caesar_analysis (can)), ++ язык текста и значения ключа для де/шифрования Цезарем и Вижинером, ++ путь к файлу для дешифрования Вернамом, в остальных случаях ничего вводит не нужно. + +Так же необходимо в последней графе загрузить файл для шифровки/дешифровки. +#### Результат программы будет выведен ниже, а также сохранен в отдельный файл. (Подробнее это можно изучить, перейдя на ветку Project в файл README.md)