#!/usr/bin/env ruby

$:.unshift(File.join(File.dirname(__FILE__), '..', '..', '..'))

require 'test/unit'
require 'rex/encoding/xor/generic'

module Rex::Encoding::Xor

class Generic::UnitTest < ::Test::Unit::TestCase

	def enc
		Generic
	end

	def hook_static_encode(data, key, expected)
		if enc.keysize != 0 && key.length != enc.keysize
			assert_raise(::ArgumentError) { enc.encode(data,key) }
		else
			assert_equal(enc.encode(data, key), [ expected, key ])
		end
	end

	def test_static_encode
		# Test key of zero length
		assert_raise(::ArgumentError) { enc.encode("\x00", "") }

		# Test non-string key
		assert_raise(::ArgumentError) { enc.encode("\x00\x01", 1) }

		# some simple single byte tests with 0x00
		30.times {
			byte = rand(256).chr
			hook_static_encode("\x00" * 3, byte, byte * 3)
		}

		# misc tests, see below
		misc_tests.each { |test|
			hook_static_encode(test[0], test[1], test[2])
		}

	end

	#
	# Misc (mostly) autogenerated tests, we need more with
	# different keysizes!
	#

	def misc_tests
		[

		# a 3 byte key test
		[
		  "\x54\x9a\x04\x02\x8f",
		  "\x6d\x4b\x3c",
		  "9\3218o\304"
		],

		# a 4 byte key test
		[
		  "\312/\216e\265\301\323\026Y\315",
		  "m2{b",
		  "\247\035\365\a\330\363\250t4\377"
		],

		# randomly generated 2 byte key tests...
		[
		  "\x82\x3f\xb4\x77\x55\x16\x4a\x56\x87\xad\x5b\xf5",
		  "\x33\xdb",
		  "\xb1\xe4\x87\xac\x66\xcd\x79\x8d\xb4\x76\x68\x2e"
		],
		[
		  "\x9c\xbd\xaa\x83\x8d\x7e\x76\xd9\x4b\xb2\x04\xd5\x2b\x58\x66",
		  "\xda\x10",
		  "\x46\xad\x70\x93\x57\x6e\xac\xc9\x91\xa2\xde\xc5\xf1\x48\xbc"
		],
		[
		  "\x7f\x3b\xfb\x3b\xce\x8c\xe8\x3d\x65\x40\x2d\x5a\x19",
		  "\x62\x28",
		  "\x1d\x13\x99\x13\xac\xa4\x8a\x15\x07\x68\x4f\x72\x7b"
		],
		[
		  "\xc8\xab\xa4\x56\xd5\xf0",
		  "\x1a\xd0",
		  "\xd2\x7b\xbe\x86\xcf\x20"
		],
		[
		  "\xcc\x5a\x84\xe0\x6c\x00\x7a\x20\xa0\xc9",
		  "\xe6\xb6",
		  "\x2a\xec\x62\x56\x8a\xb6\x9c\x96\x46\x7f"
		],
		[
		  "\x46\x96\x83\x1f\x6a\x79\xfe\xec\x24\xe0\xc3\x20\xe9\xa5\x3a\x76",
		  "\x36\x5e",
		  "\x70\xc8\xb5\x41\x5c\x27\xc8\xb2\x12\xbe\xf5\x7e\xdf\xfb\x0c\x28"
		],
		[
		  "\x74\x7c\xe9\x21\x30\x33\xb3\xe6\x77\x9e\x07\xbc\x6c\xee\xc5\x06",
		  "\x02\xa0",
		  "\x76\xdc\xeb\x81\x32\x93\xb1\x46\x75\x3e\x05\x1c\x6e\x4e\xc7\xa6"
		],
		[
		  "\x64\x8c\xc3\x41\x5d\xe5\x18\x36\xda\xc4\x86",
		  "\xe3\xb9",
		  "\x87\x35\x20\xf8\xbe\x5c\xfb\x8f\x39\x7d\x65"
		],
		[
		  "\xdb\xbb\xb2\x7c\xda\x1f\xd6\xa5\x34\x00\xad",
		  "\x20\xfc",
		  "\xfb\x47\x92\x80\xfa\xe3\xf6\x59\x14\xfc\x8d"
		],
		[
		  "\xc1\x2e\xfc\x7b\x98\x41\xec\xe3\x40\x98\x0b\xfd\x2c",
		  "\x4a\xd7",
		  "\x8b\xf9\xb6\xac\xd2\x96\xa6\x34\x0a\x4f\x41\x2a\x66"
		]
		]
	end
end
end