Class Crypt::XXTEA

  1. lib/crypt_tea/xxtea.rb
Parent: Object

Methods

public class

  1. decrypt
  2. encrypt
  3. new

public instance

  1. decrypt
  2. encrypt

Constants

DELTA = 0x9E3779B9

Public class methods

decrypt (key, ciphertext)

Decrypt the ciphertext using the key

[show source]
# File lib/crypt_tea/xxtea.rb, line 106
    def self.decrypt(key, ciphertext)
      self.new(key).decrypt(ciphertext)
    end
encrypt (key, plaintext)

Encrypt the plaintext using the key

[show source]
# File lib/crypt_tea/xxtea.rb, line 66
    def self.encrypt(key, plaintext)
      self.new(key).encrypt(plaintext)
    end
new (new_key)
[show source]
# File lib/crypt_tea/xxtea.rb, line 5
    def initialize(new_key)
      @key = str_to_longs(new_key)

      if @key.length > 4
        raise 'Key is too long (no more than 16 chars)'

      elsif @key.length == 0
        raise 'Key cannot be empty'

      elsif @key.length < 4
        @key.length.upto(4) { |i| @key[i] = 0 }

      end
    end

Public instance methods

decrypt (ciphertext)

Decrypt the ciphertext

[show source]
# File lib/crypt_tea/xxtea.rb, line 112
    def decrypt(ciphertext)
      return '' if ciphertext.length == 0

      v = str_to_longs(ciphertext.unpack('m').pack("a*"))   # base64 decode and convert to array of 'longs'
      n = v.length - 1
      z = v[n]
      y = v[0]
      q = (6 + 52 / (n + 1)).floor
      sum = int32(q * DELTA)
      p = 0

      while (sum != 0) do
        e = sum >> 2 & 3
        n.downto(1) do |i|
          z = v[i - 1]
          y = v[i] = int32(v[i] - mx(z, y, sum, i, e))
          p = i
        end

        p -= 1
        z = v[n]
        y = v[0] = int32(v[0] - mx(z, y, sum, p, e))
        sum = int32(sum - DELTA)
      end

      longs_to_str(v, true)
    end
encrypt (plaintext)

Encrypt the plaintext

[show source]
# File lib/crypt_tea/xxtea.rb, line 72
    def encrypt(plaintext)
      return '' if plaintext.length == 0

      v = str_to_longs(plaintext, true)
      v[1] = 0 if v.length == 1

      n = v.length - 1

      z = v[n]
      y = v[0]
      q = (6 + 52 / (n + 1)).floor
      sum = 0
      p = 0

      while(0 <= (q -= 1)) do
        sum = int32(sum + DELTA)
        e = sum >> 2 & 3

        n.times do |i|
          y = v[i + 1];
          z = v[i] = int32(v[i] + mx(z, y, sum, i, e))
          p = i
        end

        p += 1
        y = v[0];
        z = v[p] = int32(v[p] + mx(z, y, sum, p, e))
      end

      longs_to_str(v).unpack('a*').pack('m').delete("\n") # base64 encode it without newlines
    end