Skip to content

Instantly share code, notes, and snippets.

@spellancer
Created May 1, 2014 12:13
Show Gist options
  • Save spellancer/8e88ed723609dec787cc to your computer and use it in GitHub Desktop.
Save spellancer/8e88ed723609dec787cc to your computer and use it in GitHub Desktop.
XOR cipher
# Гаммирование
class String
def ^( other )
b1 = self.unpack("U*")
b2 = other.unpack("U*")
longest = [b1.length,b2.length].max
b1 = [0]*(longest-b1.length) + b1
b2 = [0]*(longest-b2.length) + b2
b1.zip(b2).map{ |a,b| a^b }.pack("U*")
end
def xor(key)
text = dup
text.length.times {|n| text[n] ^= key[n] }
text
end
end
puts "Метод гаммирования"
print "Введите исходный текст: "
text = gets
print "\nВведите ключевое слово: "
keyword = gets
text.gsub!(/\s+/, '')
keyword.chomp!
if keyword.size < text.size
ta = text.scan(/.{#{keyword.size}}/)
else
ta = []
while text.size < keyword.size
text << '-'
end
ta.push(text)
end
print "\n ta = #{ta}; keyword = #{keyword} \n"
res = ""
ta.each do |v|
# r = v ^ keyword
r = v.xor(keyword)
p r
res << r
end
puts "Зашифрованное сообщение: "
p res
puts "\nРасшифровка: \n"
it = res.xor(text)
rr = res.xor(it)
puts "Ключ: "
p it
puts "Исходное сообщение: "
p rr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment