Дешифратор виженера на питоне

dssstr / vigenere.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

def encrypt ( plaintext , key ):
key_length = len ( key )
key_as_int = [ ord ( i ) for i in key ]
plaintext_int = [ ord ( i ) for i in plaintext ]
ciphertext = »
for i in range ( len ( plaintext_int )):
value = ( plaintext_int [ i ] + key_as_int [ i % key_length ]) % 26
ciphertext += chr ( value + 65 )
return ciphertext
def decrypt ( ciphertext , key ):
key_length = len ( key )
key_as_int = [ ord ( i ) for i in key ]
ciphertext_int = [ ord ( i ) for i in ciphertext ]
plaintext = »
for i in range ( len ( ciphertext_int )):
value = ( ciphertext_int [ i ] — key_as_int [ i % key_length ]) % 26
plaintext += chr ( value + 65 )
return plaintext

I think there are limitations here with lower case and capital letters. You’d need to check for .lower() , and also simply pass the character through if it doesn’t match A-Z.

I wrote one that handles all default ASCII characters (95):

def vig(txt='', key='', typ='d'): if not txt: print 'Needs text' return if not key: print 'Needs key' return if typ not in ('d', 'e'): print 'Type must be "d" or "e"' return k_len = len(key) k_ints = [ord(i) for i in key] txt_ints = [ord(i) for i in txt] ret_txt = '' for i in range(len(txt_ints)): adder = k_ints[i % k_len] if typ == 'd': adder *= -1 v = (txt_ints[i] - 32 + adder) % 95 ret_txt += chr(v + 32) print ret_txt return ret_txt 
q = vig('Let\'s check this out!', 'super secret key', 'e') ` 
vig(q, 'super secret key', 'd') Let's check this out! 
universe = [c for c in (chr(i) for i in range(32,127))] uni_len = len(universe) def vign(txt='', key='', typ='d'): if not txt: print 'Needs text.' return if not key: print 'Needs key.' return if typ not in ('d', 'e'): print 'Type must be "d" or "e".' return if any(t not in universe for t in key): print 'Invalid characters in the key. Must only use ASCII symbols.' return ret_txt = '' k_len = len(key) for i, l in enumerate(txt): if l not in universe: ret_txt += l else: txt_idx = universe.index(l) k = key[i % k_len] key_idx = universe.index(k) if typ == 'd': key_idx *= -1 code = universe[(txt_idx + key_idx) % uni_len] ret_txt += code print ret_txt return ret_txt 

@flipperbw ,
I'm trying to make a similar program. Would you mind reposting your code with comments; I'm having a bit of a hard time following it.
Thanks.

I implemented this some years ago, along with a tabula recta generator so you can do it by hand (for fun!)

Hello!
in your first code (the one that starts like:
def vig(txt='', key='', typ='d'):
if not txt:
print 'Needs text')
there is a thing called "ret_text"
what does it do? I am trying to get inputs and then encode/decode it but I am not sure how I should do that, if only I knew what ret_text does. Can you specify it?
Thanks!

It's just the return text, that one by one figures out the proper character to return given the key. It's been a while since I wrote this snippet but if it can find a match of an ascii character, itll convert that, else it will leave it alone.

I think there are limitations here with lower case and capital letters. You'd need to check for .lower() , and also simply pass the character through if it doesn't match A-Z.

I wrote one that handles all default ASCII characters (95):

def vig(txt='', key='', typ='d'): if not txt: print 'Needs text' return if not key: print 'Needs key' return if typ not in ('d', 'e'): print 'Type must be "d" or "e"' return k_len = len(key) k_ints = [ord(i) for i in key] txt_ints = [ord(i) for i in txt] ret_txt = '' for i in range(len(txt_ints)): adder = k_ints[i % k_len] if typ == 'd': adder *= -1 v = (txt_ints[i] - 32 + adder) % 95 ret_txt += chr(v + 32) print ret_txt return ret_txt 
q = vig('Let\'s check this out!', 'super secret key', 'e') ` 
vig(q, 'super secret key', 'd') Let's check this out! 

I like the way your code works but I dislike its readability

import tkinter as tk
from tkinter import ttk
from tkinter import *

root.geometry('826x567')
root.configure(background='#000000')
root.title('Message Encryption and Decryption')

lblInfo=Label(root, text='. SECRET MESSAGING. \n . Vigenère cipher. ', bg='black', font=('helvetica', 22, 'normal'),fg='purple').place(x=264, y=36)

rand = StringVar()
Msg = StringVar()
key = StringVar()
mode = StringVar()
Result = StringVar()

lblReference = Label(root,bg="black", font = ('Century', 11, 'bold'),text = "NAME. ",fg="white", bd = 11, anchor = "w").place(x=98, y=197)
txtReference =Entry(root, font = ('Century', 11, 'bold'),textvariable = rand, bd = 10, insertwidth = 4,bg = "white", justify = 'right').place(x=343, y=198)
lblMsg =Label(root,bg="black", font = ('Century', 11, 'bold'),text = "MESSAGE. ",fg="white", bd = 11, anchor = "w").place(x=98, y=241)
txtMsg =Entry(root, font = ('Century', 11, 'bold'),textvariable = Msg, bd = 10, insertwidth = 4,bg = "white", justify = 'right').place(x=343, y=241)
lblkey =Label(root,bg="black", font = ('Century', 11, 'bold'),text = "KEY. ",fg="white", bd = 11, anchor = "w").place(x=98, y=274)
txtkey =Entry(root, font = ('Century', 11, 'bold'),textvariable = key,fg="black", bd = 10, insertwidth = 4,bg = "white", justify = 'right').place(x=343, y=275)
lblmode =Label(root,bg="black", font = ('Century', 11, 'bold'),text = "Mode==",fg="white", bd = 11, anchor = "w").place(x=98, y=316)
txtmode =Entry(root, font = ('Century', 11, 'bold'),textvariable = mode, bd = 10, insertwidth = 4,bg = "white", justify = 'right').place(x=343, y=316)
lblService = Label(root,bg="black", font = ('Century', 11, 'bold'),text = "The Result--",fg="white", bd = 11, anchor = "w").place(x=98, y=354)
txtService = Entry(root, font = ('Century', 11, 'bold'),textvariable = Result, bd = 10, insertwidth = 4,bg = "white", justify = 'right').place(x=343, y=354)

for i in range(len(clear)): key_c = key[i % len(key)] enc_c = chr((ord(clear[i]) + ord(key_c)) % 256) enc.append(enc_c) return base64.urlsafe_b64encode("".join(enc).encode()).decode() 
enc = base64.urlsafe_b64decode(enc).decode() for i in range(len(enc)): key_c = key[i % len(key)] dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256) dec.append(dec_c) return "".join(dec) 

def Ref():
print("Message notranslate"> clear = Msg.get() k = key.get() m = mode.get() if (m == 'e'): Result.set(encode(k, clear)) else: Result.set(decode(k, clear))

btnTotal =Button(root, text='Show Message', bg='#7FFF00', font=('verdana', 12, 'normal'), command=Ref).place(x=112, y=444)
btnReset =Button(root, text='Reset', bg='#FF3030', font=('verdana', 12, 'normal'), command=Reset).place(x=250, y=444)
btnExit =Button(root, text='Exit', bg='#A020F0', font=('verdana', 12, 'normal'), command=qExit).place(x=315, y=444)

Источник

Vigenere Cipher Using Python

In this article, we will learn Vigenere Cipher using Python. First, let’s discuss a few points vigenere cipher.

What is Vigenere Cipher

Vigenere Cipher is a technique for encrypting alphabetic content. It utilizes a basic type of polyalphabetic replacement. A polyalphabetic cipher is any cipher dependent on replacement, utilizing numerous replacement alphabets.

The table comprises of the letters in order worked out multiple times in various lines, every letter set moved consistently to one side contrasted with the past letters in order, comparing to the 26 potential Caesar Ciphers.

At various focuses in the encryption cycle, the cipher utilizes alternate letters in order from one of the lines. The letters in order utilized at each point rely upon a rehashing catchphrase.

Encryption – (message+key) % 26

Decryption – (encrytption text-key+26)%26

Vigenere Cipher in Python

1. Firstly, a key is generated with the help of a keyword if the length of the message is not equal to the keyword.

2. Use generateKey function to generate the key. The keyword is appended to itself until the length of the message is equal to the length of the key.

3. Once the key generated use encryption() to encrypt the message which takes two arguments one is the message that needs to be encrypted and the second argument is the key that returns the encrypted text.

4. In the encryption function the message and key are added modulo 26

5. Use the decryption function to decrypt the encrypted message. That takes two arguments one is the encrypted text and the second one is the key that used for encryption.

6. In the decryption function encryption text and key are subtracted, then added 26 modulo 26.

7. Finally, return the encrypted and decrypted messages.

def generateKey(string, key): key = list(key) if len(string) == len(key): return(key) else: for i in range(len(string) -len(key)): key.append(key[i % len(key)]) return("" . join(key)) def encryption(string, key): encrypt_text = [] for i in range(len(string)): x = (ord(string[i]) +ord(key[i])) % 26 x += ord('A') encrypt_text.append(chr(x)) return("" . join(encrypt_text)) def decryption(encrypt_text, key): orig_text = [] for i in range(len(encrypt_text)): x = (ord(encrypt_text[i]) -ord(key[i]) + 26) % 26 x += ord('A') orig_text.append(chr(x)) return("" . join(orig_text)) if __name__ == "__main__": string = input("Enter the message: ") keyword = input("Enter the keyword: ") key = generateKey(string, keyword) encrypt_text = encryption(string,key) print("Encrypted message:", encrypt_text) print("Decrypted message:", decryption(encrypt_text, key))
Enter the message: CODESPEEDY Enter the keyword: TIME Encrypted message: BCVORDWOCM Decrypted message: CODESPEEDY

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Криптоанализ шифра Виженера на Python с поддержкой русского языка

olekzonder/VigenereHacker

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Криптоанализ шифра Виженера на Python с поддержкой русского языка

Грубый перебор по словарю

Криптоанализ шифра Цезаря с помощью частотного анализа

main.py - основная программа

CaesarShiftHacker.py - подбор возможного сдвига шифра Цезаря

DetectLanguage.py - обнаружение русского или английского языка по словарю

DictionaryHacker.py - грубый перебор по словарю

FreqAnalysis.py - частотный анализ

IndexOfCoincidence.py - индекс совпадений

Kasiski.py - анализ Касиски

KeyFinder.py - подбор ключа исходя из сдвигов шифра Цезаря

VigenereDecrypt.py - дешифратор шифра Виженера

Python 3.x, используются лишь встроенные библиотеки

Файлы ввода-вывода будут находиться в папке куда был склонирован репозиторий.

изображение

About

Криптоанализ шифра Виженера на Python с поддержкой русского языка

Источник

Читайте также:  Css button hover focus
Оцените статью