Class: Origami::Encryption::ARC4

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

Overview

Pure Ruby implementation of the aRC4 symmetric algorithm

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ ARC4

Creates and initialises a new aRC4 generator using given key



548
549
550
551
552
553
554
# File 'lib/origami/encryption.rb', line 548

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



541
542
543
# File 'lib/origami/encryption.rb', line 541

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

.encrypt(key, data) ⇒ Object

Encrypts data using the given key



534
535
536
# File 'lib/origami/encryption.rb', line 534

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

Instance Method Details

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

Encrypt/decrypt data with the aRC4 encryption algorithm



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/origami/encryption.rb', line 559

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