7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/crypt/noise.rb', line 7
def add_noise(new_length)
message = self
usable_noisy_message_length = new_length / 9 * 8
bitmap_size = new_length / 9
remaining_bytes = new_length - usable_noisy_message_length - bitmap_size
if (message.length > usable_noisy_message_length)
minimumnew_length = (message.length / 8.0).ceil * 9
puts "For a clear text of #{message.length} bytes, the minimum obscured length"
puts "is #{minimumnew_length} bytes which allows for no noise in the message."
puts "You should choose an obscured length of at least double the clear text"
puts "length, such as #{message.length / 8 * 32} bytes"
raise "Insufficient length for noisy message"
end
bitmap = []
usable_noisy_message_length.times { bitmap << false }
srand(Time.now.to_i)
positions_selected = 0
while (positions_selected < message.length)
position_taken = rand(usable_noisy_message_length)
if bitmap[position_taken]
next
else
bitmap[position_taken] = true
positions_selected = positions_selected.next
end
end
noisy_message = ""
0.upto(bitmap_size-1) { |byte|
c = 0
0.upto(7) { |bit|
c = c + (1<<bit) if bitmap[byte * 8 + bit]
}
noisy_message << c.chr
}
pos_in_message = 0
0.upto(usable_noisy_message_length-1) { |pos|
if bitmap[pos]
meaningful_byte = message[pos_in_message]
noisy_message << meaningful_byte
pos_in_message = pos_in_message.next
else
noise_byte = rand(256).chr
noisy_message << noise_byte
end
}
remaining_bytes.times {
noise_byte = rand(256).chr
noisy_message << noise_byte
}
return(noisy_message)
end
|