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



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

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



539
540
541
# File 'lib/origami/encryption.rb', line 539

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

.encrypt(key, data) ⇒ Object

Encrypts data using the given key



532
533
534
# File 'lib/origami/encryption.rb', line 532

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



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

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