Skip to content

Instantly share code, notes, and snippets.

@CliveIMPISA
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CliveIMPISA/571d36cafc14ffbff082 to your computer and use it in GitHub Desktop.
Save CliveIMPISA/571d36cafc14ffbff082 to your computer and use it in GitHub Desktop.
This is a test file.
There are many like it.
But this test file is mine.
#!/usr/bin/env ruby
require_relative 'xor_helper'
if ARGV.count < 2
puts "Usage: xor_defend [infile] [key]\n\n"
exit
end
filename = ARGV[0]
key = ARGV[1]
begin
file = File.read(filename)
print XorHelper.encode(file, key)
rescue => e
puts "Could not read file: #{e}"
end
## Example usage:
# ruby xor_defend.rb test.txt key > out.txt
# cat out.txt
# ruby xor_defend.rb out.txt key
# Author: Clive Augustin, Tiffany Fontenelle-Augustin & Chen Li Zhan)
# XorHelper provides an encode method to xor a file with a key
module XorHelper
# XOR encodes/decodes a document with a key
# Parameters:
# doc: string
# key: string
# Returns: string
def self.encode(doc, key)
# Enter all your code into this method (only!)
# converts key and and doc to arrays
doc_array = doc.chars.map {|c| c}
key_array = key.chars.map {|k| k}
# key and doc zip together with rotating key
doc_and_rotated_key = doc_array.zip(key_array.cycle)
# Encryption or De-Encryption returned using xor :)
return doc_and_rotated_key.map { |e,i| (e.ord ^ i.ord).chr}.join
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment