Взлом Vigenere cipher — различия между версиями
Материал из InformationSecurity WIKI
Drakylar (обсуждение | вклад) м (→python) |
Drakylar (обсуждение | вклад) м |
||
| Строка 37: | Строка 37: | ||
==ruby== | ==ruby== | ||
| + | <syntaxhighlight lang="ruby" line> | ||
| + | module VigenereCipher | ||
| + | |||
| + | BASE = 'A'.ord | ||
| + | SIZE = 'Z'.ord - BASE + 1 | ||
| + | |||
| + | def encrypt(text, key) | ||
| + | crypt(text, key, :+) | ||
| + | end | ||
| + | |||
| + | def decrypt(text, key) | ||
| + | crypt(text, key, :-) | ||
| + | end | ||
| + | |||
| + | def crypt(text, key, dir) | ||
| + | text = text.upcase.gsub(/[^A-Z]/, '') | ||
| + | key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle | ||
| + | text.each_char.inject('') do |ciphertext, char| | ||
| + | offset = key_iterator.next | ||
| + | ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr | ||
| + | end | ||
| + | end | ||
| + | |||
| + | end | ||
| + | </syntaxhighlight> | ||
| + | |||
==bash== | ==bash== | ||
Версия 12:07, 1 июня 2016
Содержание
Где часто используется
Скрипты
python
encrypt
def encryption(plaintext, keyword):
txt_len = len(plaintext)
keyword *= txt_len // len(keyword) + 1
keyword = keyword[:txt_len]
encoded = ""
for c in range(txt_len):
newchar = ord(plaintext[c]) + ord(keyword[c]) - 194
newchar %= 25
encoded += chr(newchar + 97)
return encodeddecrypt
def decrypt(key, ciphertext):
from itertools import cycle
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
pairs = zip(ciphertext, cycle(key))
result = ''
for pair in pairs:
total = reduce(lambda x, y: ALPHA.index(x) - ALPHA.index(y), pair)
result += ALPHA[total % 26]
return resultperl
ruby
module VigenereCipher
BASE = 'A'.ord
SIZE = 'Z'.ord - BASE + 1
def encrypt(text, key)
crypt(text, key, :+)
end
def decrypt(text, key)
crypt(text, key, :-)
end
def crypt(text, key, dir)
text = text.upcase.gsub(/[^A-Z]/, '')
key_iterator = key.upcase.gsub(/[^A-Z]/, '').chars.map{|c| c.ord - BASE}.cycle
text.each_char.inject('') do |ciphertext, char|
offset = key_iterator.next
ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr
end
end
end