Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 5th, 2012  |  syntax: None  |  size: 1.82 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class Steganography
  2.  
  3.    class << self    
  4.    
  5.        def load_text(file_name)
  6.          file = File.open file_name, "r"
  7.          @text = file.read.chars.inject("") { |str, chr| str += "%08b" % chr.ord }
  8.        end
  9.    
  10.        def load_image(bmp_file)  
  11.          @image = IO.read(bmp_file)
  12.          @offset = @image[10..14].unpack('L*')[0]
  13.          @image_array = @image[@offset..-1]        
  14.        end  
  15.        
  16.        def load_files(bmp_file, file_name = nil)
  17.           load_image(bmp_file)
  18.           load_text(file_name) unless file_name.nil?
  19.        end
  20.            
  21.       def create_image(image_array)
  22.          @image[0..@offset-1] + image_array
  23.       end
  24.          
  25.       def encode(bmp_file, file_name)
  26.         load_files(bmp_file, file_name)  
  27.        
  28.         i = 0      
  29.         encoded_image_array = @image_array.bytes.map do |byte|
  30.             if i < @text.size
  31.               if @text[i] == '1'  
  32.                 byte |= 1 << 0      
  33.               elsif @text[i] == '0'
  34.                 byte &= ~(1 << 0)
  35.               end
  36.               i += 1    
  37.             else
  38.               byte &= ~(1 << 0)
  39.             end    
  40.             byte
  41.          end                  
  42.                                    
  43.        File.open("output.bmp", "w") do |f|
  44.          f.write  create_image(encoded_image_array.pack('C*').force_encoding('utf-8'))
  45.        end
  46.      
  47.       end
  48.  
  49.       def decode(bmp_file)
  50.         load_files(bmp_file)  
  51.         decoded_string = @image_array.bytes.inject([]) { |string, byte| string << (byte & (1 << 0)) }                                                
  52.         [decoded_string.join("")].pack('B*').unpack('A*')[0]                  
  53.       end
  54.    
  55.    end    
  56. end
  57.  
  58. Steganography.encode("input.bmp", "input.txt")            
  59. p Steganography.decode("output.bmp")