Module: SubstitutionCipher

Defined in:
lib/accu-cipher.rb

Overview

Module containing the classes and methods of the library.

Constant Summary collapse

ALPHA_RANGE =
97..122

Class Method Summary collapse

Class Method Details

.crack_offset(string) ⇒ Object

A method to crack (with the users help) a string that has been “encrypted” with SubstitutionCipher#encrypt.



90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/accu-cipher.rb', line 90

def self.crack_offset(string)
	first = Time.now
	range = 1..25
	complete = false
	range.to_a.each do |value|
		puts "\n-------------\n\n"
		puts self.decrypt(string,value)
		puts "\n-------------\n\n"
		puts "Valid? |Y N|"
		result = gets.chomp.downcase
		if result == "y" then
			complete = value
			break
		end
	end
	puts "\n-------------\n\n"
	if not complete then
		puts "Crack failed."
	else
		puts "Offset: #{complete}\nTime taken: #{Time.now-first}"
	end
	return complete
end

.decrypt(string, offset = 3) ⇒ Object

“Decrypt” a string via a substitution cipher.



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/accu-cipher.rb', line 70

def self.decrypt(string,offset=3)
	string = self.purge_nonalpha string
	final = ""
	string.split("").each_with_index do |source,index|
		if (not source.ord == 10 and not source.ord == 32) then
			result = source.ord - offset
			if not SubstitutionCipher::ALPHA_RANGE.include? source.ord then
				result += 25
			end
		else
			result = source.ord
		end
		final << result.chr
	end
	return final
end

.encrypt(string, offset = 3) ⇒ Object

“Encrypt” a string via a substitution cipher.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/accu-cipher.rb', line 51

def self.encrypt(string,offset=3)
	string = self.purge_nonalpha string
	final = ""
	string.split("").each_with_index do |source,index|
		if (not source.ord == 10 and not source.ord == 32) then
			result = source.ord + offset
			if not SubstitutionCipher::ALPHA_RANGE.include? source.ord then
				result -= 25
			end
		else
			result = source.ord
		end
		final << result.chr
	end
	return final
end

.purge_nonalpha(text) ⇒ Object

Remove non-alphabetical letters from plaintext (bar spaces and newlines)



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/accu-cipher.rb', line 35

def self.purge_nonalpha(text)
	text = text.dup.downcase
	table = []
	text.split("").each_with_index do |source,index|
		if not SubstitutionCipher::ALPHA_RANGE.include? source.ord and (not source.ord == 10 and not source.ord == 32) then
			table << index
		end
	end
	table.reverse.each do |index|
		text[index] = ""
	end
	return text
end