Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,18 @@
# Python-Efimova-121
# Веб версия шифровальщика
## Прочитать о непосредствнной работе программы можно, перейдя на ветку 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)
7 changes: 7 additions & 0 deletions encryption/alphabet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#alphabets
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
alphabet_vig = 'ABCDEFGHIJKLMNOPQRSTUVWXYZАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ><?.,/\|@#$!^&*()_+=-1234567890`~;:"[]{}'
alphabet_vigru = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ><?.,/\|@#$!^&*()_+=-1234567890`~;:"[]{}'
alphabet_vigeu = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ><?.,/\|@#$!^&*()_+=-1234567890`~;:"[]{}'
alphabet_EU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alphabet_RU = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
70 changes: 70 additions & 0 deletions encryption/caesar_an.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
from alphabet import *

rate_BOTH = [0.082, 0.015, 0.028, 0.043, 0.13, 0.022, 0.02, 0.061, 0.07, 0.0015, 0.0077, 0.04, 0.024, 0.067, 0.075, 0.019, 0.00095, 0.06, 0.063, 0.091, 0.028, 0.0098, 0.024, 0.0015, 0.02, 0.00074, 0.062, 0.014, 0.038, 0.013, 0.025, 0.072, 0.00031, 0.007, 0.016, 0.062, 0.010, 0.028, 0.035, 0.026, 0.053, 0.09, 0.023, 0.04, 0.045, 0.053, 0.021, 0.002, 0.009, 0.004, 0.012, 0.006, 0.000312, 0.016, 0.014, 0.003, 0.006, 0.018]
rate_RU = [0.062, 0.014, 0.038, 0.013, 0.025, 0.072, 0.00031, 0.007, 0.016, 0.062, 0.010, 0.028, 0.035, 0.026, 0.053, 0.09, 0.023, 0.04, 0.045, 0.053, 0.021, 0.002, 0.009, 0.004, 0.012, 0.006, 0.003, 0.000312, 0.016, 0.014, 0.003, 0.006, 0.018]
rate_EN = [0.082, 0.015, 0.028, 0.043, 0.13, 0.022, 0.02, 0.061, 0.07, 0.0015, 0.0077, 0.04, 0.024, 0.067, 0.075, 0.019, 0.00095, 0.06, 0.063, 0.091, 0.028, 0.0098, 0.024, 0.0015, 0.02, 0.00074]

def find_shift(text, ord_alpha, rate_al, alpha):
rate=[0 for _ in range(len(ord_alpha))]
space = 0
enru = False
if len(ord_alpha) > 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)
59 changes: 59 additions & 0 deletions encryption/caesar_ciph.py
Original file line number Diff line number Diff line change
@@ -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

35 changes: 35 additions & 0 deletions encryption/encryption.py
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions encryption/file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Князь Василий говорил всегда лениво, как актер говорит роль старой пиесы. Анна Павловна Шерер, напротив, несмотря на свои сорок лет, была преисполнена оживления и порывов.
Быть энтузиасткой сделалось ее общественным положением, и иногда, когда ей даже того не хотелось, она, чтобы не обмануть ожиданий людей, знавших ее, делалась энтузиасткой. Сдержанная улыбка, игравшая постоянно на лице Анны Павловны, хотя и не шла к ее отжившим чертам, выражала, как у избалованных детей, постоянное сознание своего милого недостатка, от которого она не хочет, не может и не находит нужным исправляться.
В середине разговора про политические действия Анна Павловна разгорячилась.
— Ах, не говорите мне про Австрию! Я ничего не понимаю, может быть, но Австрия никогда не хотела и не хочет войны. Она предает нас. Россия одна должна быть спасительницей Европы. Наш благодетель знает свое высокое призвание и будет верен ему. Вот одно, во что я верю. Нашему доброму и чудному государю предстоит величайшая роль в мире, и он так добродетелен и хорош, что Бог не оставит его, и он исполнит свое призвание задавить гидру революции, которая теперь еще ужаснее в лице этого убийцы и злодея. Мы одни должны искупить кровь праведника. На кого нам надеяться, я вас спрашиваю.. Англия с своим коммерческим духом не поймет и не может понять всю высоту души императора Александра. Она отказалась очистить Мальту. Она хочет видеть, ищет заднюю мысль наших действий. Что они сказали Новосильцеву Ничего. Они не поняли, они не могли понять самоотвержения нашего императора, который ничего не хочет для себя и все хочет для блага мира. И что они обещали Ничего. И что обещали, и того не будет! Пруссия уже объявила, что Бонапарте непобедим и что вся Европа ничего не может против него..
9 changes: 9 additions & 0 deletions encryption/main.py
Original file line number Diff line number Diff line change
@@ -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)
25 changes: 25 additions & 0 deletions encryption/vernam_ciph.py
Original file line number Diff line number Diff line change
@@ -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)
109 changes: 109 additions & 0 deletions encryption/vigenere_ciph.py
Original file line number Diff line number Diff line change
@@ -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)