Class: CryptoToolchain::BlackBoxes::MT19937StreamCipher

Inherits:
Object
  • Object
show all
Defined in:
lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb

Constant Summary collapse

MAX_SEED =
0x0000ffff

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(plaintext, seed: rand(0..(self.class.max_seed))) ⇒ MT19937StreamCipher

Returns a new instance of MT19937StreamCipher.



19
20
21
22
23
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 19

def initialize(plaintext, seed: rand(0..(self.class.max_seed)))
  @seed = seed & self.class.max_seed
  @prng = CryptoToolchain::Utilities::MT19937.new(@seed)
  @plaintext = plaintext
end

Class Method Details

.generate_token(length: 32, seed: Time.now.to_i) ⇒ Object



15
16
17
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 15

def self.generate_token(length: 32, seed: Time.now.to_i)
  new("A" * length, seed: seed).keystream.to_base64
end

.max_seedObject



6
7
8
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 6

def max_seed
  @max_seed ||= MAX_SEED
end

.max_seed=(val) ⇒ Object



10
11
12
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 10

def max_seed=(val)
  @max_seed = val
end

Instance Method Details

#decrypt(str) ⇒ Object



29
30
31
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 29

def decrypt(str)
  str ^ keystream
end

#encrypt(str = plaintext) ⇒ Object



25
26
27
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 25

def encrypt(str = plaintext)
  str ^ keystream
end

#keystreamObject



33
34
35
36
37
38
39
# File 'lib/crypto_toolchain/black_boxes/mt_19937_stream_cipher.rb', line 33

def keystream
  return @keystream if defined? @keystream
  _keystream = (0..(plaintext.bytesize / 4)).each_with_object("") do |_, memo|
    memo << [prng.extract].pack("L")
  end
  @keystream = _keystream[0...(plaintext.bytesize)]
end