Class: Origami::Encryption::RC4

Inherits:
Object
  • Object
show all
Defined in:
lib/origami/encryption.rb

Overview

Pure Ruby implementation of the RC4 symmetric algorithm

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ RC4

Creates and initialises a new RC4 generator using given key



610
611
612
613
614
615
616
# File 'lib/origami/encryption.rb', line 610

def initialize(key)
    if Origami::OPTIONS[:use_openssl]
        @key = key
    else
        @state = init(key)
    end
end

Class Method Details

.decrypt(key, data) ⇒ Object

Decrypts data using the given key



603
604
605
# File 'lib/origami/encryption.rb', line 603

def RC4.decrypt(key, data)
    RC4.new(key).decrypt(data)
end

.encrypt(key, data) ⇒ Object

Encrypts data using the given key



596
597
598
# File 'lib/origami/encryption.rb', line 596

def RC4.encrypt(key, data)
    RC4.new(key).encrypt(data)
end

Instance Method Details

#cipher(data) ⇒ Object Also known as: encrypt, decrypt

Encrypt/decrypt data with the RC4 encryption algorithm



621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/origami/encryption.rb', line 621

def cipher(data)
    return "" if data.empty?

    if Origami::OPTIONS[:use_openssl]
        rc4 = OpenSSL::Cipher::RC4.new.encrypt
        rc4.key_len = @key.length
        rc4.key = @key

        output = rc4.update(data) << rc4.final
    else
        output = ""
        i, j = 0, 0
        data.each_byte do |byte|
            i = i.succ & 0xFF
            j = (j + @state[i]) & 0xFF

            @state[i], @state[j] = @state[j], @state[i]

            output << (@state[@state[i] + @state[j] & 0xFF] ^ byte).chr
        end
    end

    output
end